<?php
define('COLOR_NAME', '颜色');
define('COLOR_VALUE', 'color');
define('MAX_TAG_DISPLAY_COUNT', 6);
Vendor('PHPExcel.PHPExcel.IOFactory');
Vendor('PHPExcel.PHPExcel.Exception');
class ProductAction extends Action {
	/**获取所有产品列表
	 * @param bool $ispoint 是否积分兑换   是-1/ 否—不传
	 * @param string $name 商品名称搜索字段
	 * @param string $isRemoved 0-上架、1-下架
	 * @param string $brand 品牌搜索字段
	 * @param string $supplierName
	 * @param string $categoryName
	 * @param int $start 分页起始
	 * @param int $limit 分页偏移
	 * @param string $order 排序字段
	 * @param string $orderBy 正序-asc、倒序desc
	 * @param bool $isExport 导出
	 * @param null $isAll
	 * @param null $cId
	 * @param null $serialNumber
	 * @param null $vendor 供应商
	 * @param null $tagName 展示分类
	 */
	public function  getAllProduct($ispoint=false, $name='',$isRemoved='', $brand='',$supplierName='',$categoryName='', $start = 0, $limit = 25,
			$order = 'prod.updateTime', $orderBy = 'desc', $isExport = false,$isAll=null,$cId=null,$serialNumber=null,$vendor=null,$tagName=null, $fromPoints = null, $supportSpecification = null, $needReturn = 0){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$ProductModel  = M('module_product');
		$supplyChainProduct = M("module_supply_chain_product");
		$condition['prod.deleted']=0;
		$condition['m.module']='product';
		if(!$isAll){
			$condition['prod.fromCustomerId']=array("eq",$customerId);
		}else{
			$cId?$condition['prod.fromCustomerId']=array("eq",$cId):"";
		}
		//判断是否积分兑换参数并设置查询条件
		isset($ispoint) && !$ispoint ? $condition['prod.fixedPrice'] = array('exp', 'IS NOT NULL'): $condition['points'] = array('exp', 'IS NOT NULL');
		isset($name) && $name != null ? $condition["prod.name"] = array("like",'%'.$name.'%'):'';
		isset($isRemoved) && $isRemoved != null ? $condition["prod.isRemoved"] = array('eq',$isRemoved):'';
		isset($brand) && $brand != null ? $condition["prod.brand"] = array("like","%{$brand}%") : "";
		isset($categoryName) && $categoryName != null ? $condition['cat.name'] = array("like","%{$categoryName}%") : "";
		isset($serialNumber) && $serialNumber ?$condition['prod.serialNumber']=array("like","%$serialNumber%"):"";
		isset($vendor) && $vendor ?$condition['ven.name']=array("like","%$vendor%"):"";
		isset($tagName) && $tagName ?$condition['tag.name']=array("like","%$tagName%"):"";
		isset($fromPoints) && $fromPoints ?$condition['prod.points'] = array('exp', 'is not null'):"";
//		isset($supportSpecification) && $supportSpecification ?$condition['prod.supportSpecification']=array("eq", 0):"";
		if (isset($supportSpecification) && $supportSpecification) {
			$condition['prod.supportSpecification']=array("eq", 0);
			$condition['prod.points'] = array('exp', 'is null');
		}
		if (!$isExport) {
			if($tagName){
				$arr = $ProductModel
					->alias('prod')
					->join("inner join wx_mishare m on m.moduleId=prod.id")
					->join("wx_mivendor ven on prod.vId=ven.id")
					->join("wx_module_product_tag_list tlist on prod.id=tlist.pid")
					->join("wx_module_product_tag tag on tlist.tagId = tag.id")
					->join("wx_mishare sta on prod.id=sta.moduleId and sta.module='product'")
					->field('prod.*,m.id as sId,ven.name as supplierName,sta.viewUv as Uv')
					->where($condition)->order("$order $orderBy")->group("prod.id")->limit($start, $limit)->select();
				if ($arr) {
					foreach($arr as $key=>$value){
						if($value['isChainPro']==1) {
							$productInfo = $ProductModel->alias("a")
								->join('wx_mivendor v ON v.id=a.vId')
								->where("a.id=".$value['supplyProId'])
								->field("a.*,v.name as vendorName")
								->find();

							$arr[$key]['serialNumber']=$productInfo['serialNumber'];
							$arr[$key]['inventoryCount']=$productInfo['inventoryCount'];
							$arr[$key]['supplyPrice']=$productInfo['channelSupplyPrice'];
							$arr[$key]['vId']=$productInfo['vId'];
							$arr[$key]['supplierName']=$productInfo['vendorName'];
							$arr[$key]['color']="#ff0000";
						}
					}
					$arr = $this->resetProductList($arr, $customerId);
					Session::switchCustomer($customerId);
					$count = $ProductModel
						->alias('prod')
						->join("inner join wx_mishare m on m.moduleId=prod.id")
						->join("wx_module_product_tag_list tlist on prod.id=tlist.pid")
						->join("wx_module_product_tag tag on tlist.tagId = tag.id")
						->join("wx_mishare sta on prod.id=sta.moduleId and sta.module='product'")
						->join("wx_mivendor ven on prod.vId=ven.id")
						->field('prod.*,m.id as sId,ven.name as supplierName,sta.viewUv')
						->group("prod.id")
						->where($condition)
						->select();
					$count= count($count);
					Output::instance()->objArray($arr,$count);
				} else {
					Output::instance()->resultCode(code_success);
				}
			}else{
				$arr = $ProductModel
					->alias('prod')
					->join("inner join wx_mishare m on m.moduleId=prod.id")
					->join("wx_mivendor ven on prod.vId=ven.id")
					->join("wx_mishare sta on prod.id=sta.moduleId and sta.module='product'")
					->field('prod.*,m.id as sId,ven.name as supplierName,sta.viewUv as uv')
					->where($condition)->order("$order $orderBy")->group("prod.id")->limit($start, $limit)->select();
				if ($arr) {
					foreach($arr as $key=>$value){
						if($value['isChainPro']==1) {
							$productInfo = $ProductModel->alias("a")
								->join('wx_mivendor v ON v.id=a.vId')
								->where("a.id=".$value['supplyProId'])
								->field("a.*,v.name as vendorName")
								->find();
							$arr[$key]['serialNumber']=$productInfo['serialNumber'];
							$arr[$key]['inventoryCount']=$productInfo['inventoryCount'];
							$arr[$key]['supplyPrice']=$productInfo['channelSupplyPrice'];
							$arr[$key]['supplierName']=$productInfo['vendorName'];
							$arr[$key]['color']="#ff0000";
						}
					}
					$arr = $this->resetProductList($arr, $customerId);
					Session::switchCustomer($customerId);
					$count = $ProductModel
						->alias('prod')
						->join("inner join wx_mishare m on m.moduleId=prod.id")
						->join("wx_mishare sta on prod.id=sta.moduleId and sta.module='product'")
						->join("wx_mivendor ven on prod.vId=ven.id")
						->field('prod.*,m.id as sId,ven.name as supplierName,sta.viewUv')
						->where($condition)
						->count();
					if ($needReturn == 1) {
						return array('data' => $arr, 'total' => $count);
					} else {
						Output::instance()->objArray($arr,$count);
					}
				} else {
					if ($needReturn == 1) {
						return;
					} else {
						Output::instance()->resultCode(code_success);
					}
				}
			}

		}else{
			$userRaletion = self::userRaletion();
			if($tagName){
				$arr = $ProductModel->alias('prod')
					->join("inner join wx_mishare m on m.moduleId=prod.id")
					->join("wx_module_product_tag_list tlist on prod.id=tlist.pid")
					->join("wx_mivendor ven on prod.vId=ven.id")
					->join("wx_module_product_tag tag on tlist.tagId = tag.id")
					->join("wx_module_product_specification spe on prod.id=spe.pid and prod.supportSpecification=1")
					->field('prod.supplyProId,prod.name,prod.salesCount,prod.supportSpecification,prod.serialNumber,prod.proSource,prod.inventory,prod.inventoryCount,prod.fixedPrice,
				prod.discountedPrice,prod.supplyPrice,prod.platCut,prod.saleCut,prod.miPrice,prod.tariff,prod.customsPrice,
				spe.serialNumber as serialNumber1,spe.fixedPrice as fixedPrice1,spe.discountedPrice as discountedPrice1,
				spe.supplyPrice as supplyPrice1,spe.platCut as platCut1,spe.saleCut as saleCut1,spe.miPrice as miPrice1,
				spe.tariff as tariff1,spe.customsPrice as customsPrice1,spe.firstSpecificName,spe.secSpecificName,spe.inventoryCount as secInventoryCount')
					->where($condition)
					->distinct(true)
					->order("$order $orderBy")->select();
			}else{
				$arr = $ProductModel->alias('prod')
					->join("inner join wx_mishare m on m.moduleId=prod.id")
					->join("wx_mivendor ven on prod.vId=ven.id")
					->join("wx_module_product_specification spe on prod.id=spe.pid and prod.supportSpecification=1")
					->field('prod.supplyProId,prod.name,prod.salesCount,prod.supportSpecification,prod.serialNumber,prod.proSource,prod.inventory,prod.inventoryCount,prod.fixedPrice,
				prod.discountedPrice,prod.supplyPrice,prod.platCut,prod.saleCut,prod.miPrice,prod.tariff,prod.customsPrice,
				spe.serialNumber as serialNumber1,spe.fixedPrice as fixedPrice1,spe.discountedPrice as discountedPrice1,
				spe.supplyPrice as supplyPrice1,spe.platCut as platCut1,spe.saleCut as saleCut1,spe.miPrice as miPrice1,
				spe.tariff as tariff1,spe.customsPrice as customsPrice1,spe.firstSpecificName,spe.secSpecificName,prod.isChainPro,spe.inventoryCount as secInventoryCount')
					->where($condition)
					->distinct(true)
					->order("$order $orderBy")->select();
			}
			foreach($arr as $key=>$value){
					if($value['isChainPro']==1) {
						if($value['supportSpecification']){
							$productInfo = $ProductModel->alias("a")
								->join('wx_mivendor v ON v.id=a.vId')
								->join("wx_module_product_specification b on a.id=b.pid and b.firstSpecificName='".$value['firstSpecificName']."' and b.secSpecificName='".$value['secSpecificName']."'")
								->where("a.id=".$value['supplyProId'])
								->field("b.*,v.name as vendorName,b.channelSupplyPrice as channelSupplyPrice1")
								->find();
							$value['serialNumber1']=$productInfo['serialNumber'];
							$value['secInventoryCount']=$productInfo['inventoryCount'];
							$value['supplyPrice1']=$productInfo['supplyPrice'];
						}else{
							$productInfo = $ProductModel->alias("a")
								->join('wx_mivendor v ON v.id=a.vId')
								->where("a.id=".$value['supplyProId'])
								->field("a.*,v.name as vendorName")
								->find();
							$value['serialNumber']=$productInfo['serialNumber'];
							$value['inventoryCount']=$productInfo['inventoryCount'];
							$value['supplyPrice']=$productInfo['supplyPrice'];
						}
						if($userRaletion['supplyRelation']==2){
							$value['supplyPrice']=$productInfo['channelSupplyPrice'];
							$value['supplyPrice1']=$productInfo['channelSupplyPrice1'];
						}
				}
				$data = null;
				$data['name']=$value['name'];

				if($value['supportSpecification']){
					$data['firstSpecificName']=$value['firstSpecificName'];
					$data['secSpecificName']=$value['secSpecificName'];
					if($value['inventory']){
						$data['inventoryCount']=$value['secInventoryCount'];
					}
					$data['serialNumber']=$value['serialNumber1'];
					$data['fixedPrice']=$value['fixedPrice1'];
					$data['discountedPrice']=$value['discountedPrice1'];
					$data['supplyPrice']=$value['supplyPrice1'];
					$data['platCut']=$value['platCut1'];
					$data['saleCut']=$value['saleCut1'];
					$data['miPrice']=$value['miPrice1'];
					if($value['proSource']){
						$data['tariff']=$value['tariff1'];
						$data['customsPrice']=$value['customsPrice1'];
					}
				}else{
					if($value['inventory']){
						$data['inventoryCount']=$value['inventoryCount'];
					}
					$data['serialNumber']=$value['serialNumber'];
					$data['fixedPrice']=$value['fixedPrice'];
					$data['discountedPrice']=$value['discountedPrice'];
					$data['supplyPrice']=$value['supplyPrice'];
					$data['platCut']=$value['platCut'];
					$data['saleCut']=$value['saleCut'];
					$data['miPrice']=$value['miPrice'];
					if($value['proSource']){
						$data['tariff']=$value['tariff'];
						$data['customsPrice']=$value['customsPrice'];
					}
				}
				$data['salesCount'] = $value['salesCount'];
				$newArr[]=$data;
			}
//			$arr = $this->resetProductList($arr, $customerId);
			$expCellName  = array(
				array('name','名称'),
				array('firstSpecificName','规格1'),
				array('secSpecificName','规格2'),
				array('inventoryCount','库存'),
				array('serialNumber','商品条码'),
				array('fixedPrice','原价'),
				array('discountedPrice','折扣价'),
				array('supplyPrice','供货价'),
				array('platCut','平台分成'),
				array('saleCut','销售分成'),
				array('miPrice','密友价'),
				array('tariff','税率'),
				array('customsPrice','报关价格'),
				array('salesCount','销量')
			);
			Session::switchCustomer($customerId);
			Output::instance()->objArrayExcel('商品展示信息', $expCellName, $newArr);
		}
	}
	//导出渠道商品
	public function getSupplyChianProduct(){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$userId = session("id");
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$supplyChianProduct = M("module_supply_chain_product");
		$customerUser = M("customer_user");
		Session::switchCustomer($customerId);
		$supplyInfo = $customerUser->alias("a")
			->join("inner join wx_module_supply_chain b on a.supplyChainId=b.id")
			->field("a.supplyRelation,b.cId,b.id")
			->where("a.id=".$userId)
			->find();
		if(!$supplyInfo){
			Output::instance()->resultCode();
			return;
		}
		$condition['prod.deleted']=0;
		$condition['prod.isRemoved']=0;
		$condition['prod.fromCustomerId']=$supplyInfo['cId'];
		$arr = $supplyChianProduct->alias("a")
			->join("inner join wx_module_product prod on a.pid=prod.id or prod.isAllChannel=1")
			->join("wx_mivendor ven on prod.vId=ven.id")
			->join("wx_module_product_specification spe on prod.id=spe.pid and prod.supportSpecification=1")
			->field("prod.*,ven.name as vendorName,spe.firstSpecificName,spe.secSpecificName,spe.inventoryCount as inventoryCount1,
			spe.serialNumber as serialNumber1,spe.fixedPrice as fixedPrice1,spe.discountedPrice as discountedPrice1,
			spe.supplyPrice as supplyPrice1,spe.channelSupplyPrice as channelSupplyPrice1,spe.platCut as platCut1,spe.saleCut as saleCut1,
			spe.miPrice as miPrice1,spe.customsName as customsName1,spe.tariff as tariff1,spe.customsPrice as customsPrice1")
			->where($condition)
			->group("prod.id")
			->select();
		foreach($arr as $key=>$value){
			$pid = $value['id'];
			if($value['isAllChannel']==1){
				$value['chainNames']='所有渠道';
			}else{
				$chains = $supplyChianProduct->alias("a")
					->join("inner join wx_customer_user b on a.cId=b.customerId and b.agent='business'")
					->where("a.pid=$pid")
					->field("group_concat(b.fullName) as chainNames")
					->find();
				$value['chainNames']=$chains['chainNames'];
			}
			$data = null;
			$data['name']=$value['name'];
			$data['brand']=$value['brand'];
			$data['vendorName']=$value['vendorName'];

			if($value['supportSpecification']){
				$data['firstSpecificName']=$value['firstSpecificName'];
				$data['secSpecificName']=$value['secSpecificName'];
				if($value['inventory']){
					$data['inventoryCount']=$value['inventoryCount1'];
				}
				$data['serialNumber']=$value['serialNumber1'];
				$data['fixedPrice']=$value['fixedPrice1'];
				$data['discountedPrice']=$value['discountedPrice1'];
				$data['supplyPrice']=$value['supplyPrice1'];
				$data['channelSupplyPrice']=$value['channelSupplyPrice1'];
				$data['platCut']=$value['platCut1'];
				$data['saleCut']=$value['saleCut1'];
				$data['miPrice']=$value['miPrice1'];
				if($value['proSource']){
					$data['tariff']=$value['tariff1'];
					$data['customsPrice']=$value['customsPrice1'];
				}
			}else{
				if($value['inventory']){
					$data['inventoryCount']=$value['inventoryCount'];
				}
				$data['serialNumber']=$value['serialNumber'];
				$data['fixedPrice']=$value['fixedPrice'];
				$data['discountedPrice']=$value['discountedPrice'];
				$data['supplyPrice']=$value['supplyPrice'];
				$data['channelSupplyPrice']=$value['channelSupplyPrice'];
				$data['platCut']=$value['platCut'];
				$data['saleCut']=$value['saleCut'];
				$data['miPrice']=$value['miPrice'];
				if($value['proSource']){
					$data['tariff']=$value['tariff'];
					$data['customsPrice']=$value['customsPrice'];
				}
			}
			$data['chainNames']=$value['chainNames'];
			if($value['proSource']){
				$data['proSource']="海外直邮";
			}else{
				$data['proSource']="普通商品";
			}
			$newArr[]=$data;
		}
		$expCellName  = array(
			array('name','名称'),
			array('brand','品牌'),
			array('vendorName','供应商'),
			array('firstSpecificName','规格1'),
			array('secSpecificName','规格2'),
			array('inventoryCount','库存'),
			array('serialNumber','商品条码'),
			array('fixedPrice','原价'),
			array('discountedPrice','折扣价'),
			array('supplyPrice','供货价'),
			array('channelSupplyPrice','渠道价'),
			array('platCut','平台分成'),
			array('saleCut','销售分成'),
			array('miPrice','密友价'),
			array('tariff','税率'),
			array('customsPrice','报关价格'),
			array('chainNames','投放渠道'),
			array('proSource','商品类型')
		);
		Output::instance()->objArrayExcel('商品展示信息', $expCellName, $newArr);
	}
	//当前用户是供应链还是渠道商
	public function userRaletion(){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$customerUser = M("customer_user");
		Session::switchCustomer($customerId);
		$id=session("id");
		$userInfo = $customerUser->where("customerId=$customerId and agent='business'")->field("supplyRelation")->find();
		$tempUserInfo = $customerUser->where("id=$id")->field("agent")->find();
		$userInfo['agent']=$tempUserInfo['agent'];
		return $userInfo;
	}
	public function resetProductList($arr, $customerId) {
		$TagListModel = M("module_product_tag_list");
		
		for($i = 0; $i < count($arr); $i++) {
			$tags = "";
			$pid = $arr[$i]["id"];
			
			$arrTag = $TagListModel->alias("taglist")->where("pid=$pid")
				->join('wx_module_product_tag tag ON taglist.tagId=tag.id')->field("taglist.*,tag.name")->select();

			$tagsId="";
			$tagsName="";

			foreach ($arrTag as $tag) {
				$tagsId .= $tag["tagId"] . ',';
				$tagsName .= $tag["name"] . ',';
			}
			if (count($arrTag) > 0) {
				$tagsId = substr($tagsId, 0, strlen($tagsId) - 1);
				$tagsName = substr($tagsName, 0, strlen($tagsName) - 1);
			}
			$arr[$i]["tagsId"] = $tagsId;
			$arr[$i]["tagsName"] = $tagsName;
		}
		return $arr;
	}

	/**
	 * @param $id 商品id，修改传id，添加传负数
	 * @param $name 商品名称
	 * @param $title 分享标题
	 * @param $vId 供应商id
	 * @param $description 分享说明
	 * @param $number 顺序号
	 * @param $unitName 单位名称
	 * @param $tags 商品展示分类id，逗号隔开
	 * @param $limitbuy 是否开启个人限购，0-不开启，1-开启
	 * @param $limitnum 个人限购数量
	 * @param int $isAllChannel 是否投放所有渠道，0-否、1-是
	 * @param $inventory 是否开启库存，0-否、1-是
	 * @param $inventoryCount 库存量（单规格）
	 * @param $webPageContent 商品详情
	 * @param $recommend 分享描述
	 * @param $accessTag 数据分析标签，用逗号隔开
	 * @param $serialNumber 商品条码（统一规格）
	 * @param $isRemoved 1-下架、0-上架
	 * @param string $picUrl 商品主图片
	 * @param string $picUrl1 商品图json（每张图片都可以添加描述）（picUrl：图片地址；picInfo：图片描述）
	 * @param null $channels
	 * @param null $vId1
	 * @param null $fixedPrice 价格（统一规格）
	 * @param null $discountedPrice 折扣价（统一规格）
	 * @param null $supplyPrice 供货价（统一规格）
	 * @param null $channelSupplyPrice 渠道价（统一规格）
	 * @param null $points
	 * @param null $pointsType
	 * @param null $categoryId
	 * @param null $shareImgs 分享主图，取分享图片第一个
	 * @param null $shareImgs1 分享图片信息json
	 * @param bool $isGroup
	 * @param int $supportSpecification 0-统一规格，1-多规格
	 * @param string $brand 品牌
	 * @param string $freeBuy
	 * @param null $freeBuyMoney
	 * @param null $picTag 商品主图标签
	 * @param null $priceTag 商品价格标签
	 * @param null $maxCopies
	 * @param int $saleCut 销售分成（统一规格）
	 * @param int $platCut 平台分成（统一规格）
	 * @param null $speciData 规格信息json
	 * @param int $tplId 展示模板id
	 * @param int $startTplId
	 * @param int $ordinary 0-非普通商品、1-普通商品
	 * @param int $teambuy 0-非团购商品、1-团购商品
	 * @param int $specialpro 1-好友特供，0-否
	 * @param null $playType 4-秒杀商品，5-好友价，null-不设置玩法
	 * @param int $totalCopies
	 * @param null $perMoney
	 * @param null $minCopies
	 * @param null $freeBuyMaterialId
	 * @param null $teamStartTime 团购开始时间
	 * @param null $teamEndTime 团购结束时间
	 * @param int $teamCount 团购人数
	 * @param int $teamPrice 团购价格
	 * @param null $teamBack 团长返现1-是、0-否
	 * @param int $teamBackMoney 团长返现金额
	 * @param int $virtual 1-虚拟商品、0非虚拟商品
	 * @param null $virtualInfo 虚拟商品使用说明
	 * @param null $virtualStartTime 虚拟商品开始日期
	 * @param null $virtualEndTime 虚拟商品结束日期
	 * @param null $json 定制信息以及任务信息以及秒杀信息
	 * @param null $miPrice 好友价
	 * @param null $distributionId 配送方式id
	 * @param int $proSource 0-普通商品、1-海外直邮
	 * @param null $microId 专区商城id
	 * @param null $weight 重量（统一规格）
	 * @param string $customsName 报关商品名称 （统一规格）
	 * @param null $customsPrice 报关价格（统一规格）
	 * @param null $tariff 税率（统一规格）
	 * @param int $activity 1-活动报名、0非活动报名
	 * @param null $activityinfo 活动报名信息
	 * @param null $foreignName 外文名称
	 * @param null $supplierSkuNo 商品编码
	 * @param null $country 国家
	 * @param null $specificUnit 规格单位（统一规格）
	 * @param null $specification 规格值（统一规格）
	 * @param null $specificName 规格名称（统一规格）
	 * @param int $logisticsStatue 是否不需要物流1不需要
	 * @param int $seckillPrice 秒杀价（统一规格）
	 * @param int $seckillSalce 秒杀分成（统一规格）
	 * @param int $seckillInventoryCount 秒杀库存（统一规格）
	 * @param null $videoUrl 商品视频
	 * @param null $videoImgUrl 商品视频封面
	 * @param null $taskModel 1-启用任务，0不启用
	 * @param int $rechargeableCard 0-非充值卡、1-充值卡
	 * @param null $rechargeAmount 充值金额
	 * @param array $unitInfo 单位信息
	 * @param int $pointSchemeId 积分方案id
	 */
	public function saveProduct($id,$name, $title,$vId,$description,$number,$unitName,$tags,$limitbuy,$limitnum,$isAllChannel=0,
								$inventory, $inventoryCount, $webPageContent, $recommend, $accessTag, $serialNumber,$isRemoved,$picUrl="",$picUrl1="",$channels=null,
								$vId1=null,$fixedPrice = NULL,$discountedPrice=NULL,$supplyPrice=NULL,$channelSupplyPrice=null,$points=NULL,$pointsType=NULL, $categoryId = NULL,
								$shareImgs = NULL,$shareImgs1 = NULL, $isGroup = false,$supportSpecification=0,$brand="",$freeBuy="0",$freeBuyMoney=null,$picTag=null,$priceTag = null,$maxCopies=NULL,
								$saleCut=0,$platCut=0, $speciData=NULL,$tplId=0,$startTplId=0,$ordinary=1,$teambuy=0,$specialpro=0,$playType=null,$totalCopies=0,$perMoney=NULL,$minCopies=NULL,$freeBuyMaterialId=NULL,
								$teamStartTime=null,$teamEndTime=null,$teamCount=0,$teamPrice=0,$teamBack=null,$teamBackMoney=0,$virtual=0,$virtualInfo=NULL,$virtualStartTime=NULL,$virtualEndTime=NULL,
								$json=NULL,$miPrice=NULL,$distributionId=NULL,$proSource=0,$microId=NULL,$weight=null,$customsName='',$customsPrice=null,$tariff=null,$activity=0,$activityinfo=NULL,$foreignName=null,
								$supplierSkuNo=null,$country=null,$specificUnit=null,$specification=null,$specificName=null,$logisticsStatue=0,$seckillPrice=0,$seckillSalce=0,$seckillInventoryCount=0,$videoUrl=null,$videoImgUrl=null
								,$taskModel=null,$pointSchemeId=-1){
//		if ($fixedPrice == 0) {
//			$fixedPrice = NULL;
//		}
		if ($discountedPrice == 0) {
			$discountedPrice = NULL;
		}
		if ($supplyPrice == 0) {
			$supplyPrice = NULL;
		}
		if ($points == 0) {
			$points = NULL;
		}
		// can not save price and points at the same time

		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		// if(!empty($accessTag)){			
		// 	addAccessTags($accessTag);
		// }


		// if ($ordinary==0 && $teambuy==0 && $specialpro==0) {
		// 	$ordinary=1;
		// }

		$cid = Session::$user["customerId"];
		$pid=$id;
		Session::switchCustomer(0);
		$ProductTagModel = M("module_product_tag");
		$ProductTagListModel = M("module_product_tag_list");
		$ProductModel = M("module_product");
		$specModel = m('module_product_specification');
		$specGroupModel = m('module_product_specification_group');
		$shareBaseModel=M("mishare");
		$shareMaterModel=M("mishare_material");
		$supplyChainPro = M("module_supply_chain_product");
        $productUnit = M("module_product_unit");

		if($id && ($pointSchemeId >= 0)){
			$relationRet = $ProductModel->where("id=$id")->save(['pointSchemeId' => $pointSchemeId]);
			if(!is_numeric($relationRet)){
				Log::write('商品关联积分方案失败:'.$ProductModel->getDbError());
				Output::instance()->object([
					'code' => -1,
					'msg' => '保存失败',
					'results' => []
				]);
				return;
			}
			Output::instance()->object([
				'code' => 0,
				'msg' => '保存成功',
				'results' => []
			]);
			return;
		}

		$time = date("Y-m-d H:i:s");
		$data["name"] = $name;
		$data["title"] = $title;
		$data["vId"] = $vId;
		$data["tplId"]=$tplId;
		$data["startTplId"]=$startTplId;
		$data["description"] = $description;
		$data["picTag"]=$picTag;
		$data["priceTag"]=$priceTag;
		$data['weight']=$weight;
		$data['customsName']=$customsName;
		$data['tariff']=$tariff;
		$data['customsPrice']=$customsPrice;
		$data["number"] = $number;
		$data["isAllChannel"] = $isAllChannel;
		$data["seckillPrice"] = $seckillPrice;
		$data["seckillSalce"] = $seckillSalce;
		$data["picUrl1"] = $picUrl1;
		$data['picUrl'] = $picUrl;
		$data["fixedPrice"] = $fixedPrice;
		$data["discountedPrice"] = $discountedPrice;
		$data['limitnum'] = $limitnum;
		isset($miPrice)&&$miPrice?$data["miPrice"] = $miPrice:"";
		$data["supplyPrice"] = $supplyPrice;
		$data['channelSupplyPrice']=$channelSupplyPrice;
		$data["platCut"]=$platCut;
		$data["saleCut"]=$saleCut;
		$data["tplId"]=$tplId;
		if(!empty($unitName)){$data["unitName"] = $unitName;}
		$data["categoryId"] = $categoryId;
		$data["inventory"] = $inventory;
		$data["inventoryCount"] = $inventoryCount;
		$data['seckillInventoryCount'] = $seckillInventoryCount;
		$data["webPageContent"] = $webPageContent;
		$data["recommend"] = $recommend;
		$data["accessTag"] = $accessTag;
		$data['brand'] = $brand;
		$data["isGroup"] = $isGroup;
		$data["ordinary"] = $ordinary;
		$data["teambuy"] = $teambuy;
		$data["specialpro"] = $specialpro;
		$data["freeBuy"]=$freeBuy;
		$data['taskModel'] = $taskModel;
		$data["foreignName"]=$foreignName;
		$data["supplierSkuNo"]=$supplierSkuNo;
		$data["country"]=$country;
		$data["specificUnit"]=$specificUnit;
		$data["specification"]=$specification;
		$data["specificName"]=$specificName;
		$data['logisticsStatue'] = $logisticsStatue;
		$data['videoUrl'] = $videoUrl;
		$data['videoImgUrl'] = $videoImgUrl;

		isset($freeBuyMoney)&&$freeBuyMoney?$data["freeBuyMoney"]=$freeBuyMoney:"";
		isset($freeBuyMaterialId)&&$freeBuyMaterialId?$data["freeBuyMaterialId"]=$freeBuyMaterialId:"";
		$data["vId1"] = $vId1;
		$data["limitbuy"]=$limitbuy;
		isset($teamStartTime)&&$teamStartTime?$data["teamStartTime"]=$teamStartTime:"";
		isset($teamEndTime)&&$teamEndTime?$data["teamEndTime"]=$teamEndTime:"";
		isset($teamCount)&&$teamCount?$data["teamCount"]=$teamCount:"";
		isset($teamPrice)&&$teamPrice?$data["teamPrice"]=$teamPrice:"";
		isset($teamBack)&&$teamBack!=null?$data["teamBack"]=$teamBack:"";
		isset($teamBackMoney)&&$teamBackMoney?$data["teamBackMoney"]=$teamBackMoney:"";

		$data["virtual"]=$virtual;
		isset($virtualInfo)&&$virtualInfo?$data["virtualInfo"]=$virtualInfo:"";
		isset($virtualStartTime)&&$virtualStartTime?$data["virtualStartTime"]=$virtualStartTime:"";
		isset($virtualEndTime)&&$virtualEndTime?$data["virtualEndTime"]=$virtualEndTime:"";
		if($id&&$id>0){
			$productInfo = $ProductModel->where("id=$id")->field("json")->find();
			$oldJson = json_decode($productInfo['json'],true);
			$newJson = json_decode($json,true);
			foreach($newJson as $key=>$value){
				$oldJson[$key]=$value;
			}
			$oldJson['customized']=$newJson['customized'];
			isset($json)&&$json?$data["json"]=json_encode($oldJson):"";
		}else{
			$data["fromCustomerId"] = $cid;
			isset($json)&&$json?$data["json"]=$json:"";
		}
		$data["playType"] = $playType;
		isset($totalCopies)&&$totalCopies?$data["totalCopies"]=$totalCopies:"";
		isset($perMoney)&&$perMoney?$data["perMoney"]=$perMoney:"";
		isset($minCopies)&&$minCopies?$data["minCopies"]=$minCopies:"";
		isset($maxCopies)&&$maxCopies?$data["maxCopies"]=$maxCopies:"";
		if($recommend == null){
			$data['recommend'] = NULL;
			
		}else{
			$data['recommend'] = $recommend;
		}

		//活动报名
		$data['activity'] = $activity;
		isset($activityinfo)&&$activityinfo?$data['activityinfo']=$activityinfo:"";
		
		$data["points"] = $points;
		$data["pointsType"] = $pointsType;
		$data["isRemoved"] = $isRemoved;
		$data["createTime"] = $time;
		$data["updateTime"] = $time;
		$data["supportSpecification"]= $supportSpecification;
		$data["distributionId"]=$distributionId;

		$data['proSource'] = $proSource;

		$data['microId'] = $microId;
		$ProductModel->startTrans();
		if($id&&$id>0) {
			if($supportSpecification!=1){
				if($serialNumber == null){
					$data["serialNumber"] = NULL;
				}else{
					$data["serialNumber"] = $serialNumber;

				}
				$proInfo = $ProductModel->where("id=$id")->field("serialNumber")->find();
				if($serialNumber&&$serialNumber!=$proInfo['serialNumber']){
					$proInfo = $ProductModel->where("serialNumber='$serialNumber' and fromCustomerId=$cid and deleted=0")->find();
					if($proInfo){
						Output::instance()->resultCode(1,"商品条码重复");
						return;
					}
				}
			}
			$resultPro = $ProductModel->where("id=$id")->save($data);
		} else{
			if($supportSpecification!=1){
				if($serialNumber == null){
					$data["serialNumber"] = NULL;
				}else{
					$data["serialNumber"] = $serialNumber;

				}
				$proInfo = $ProductModel->where("serialNumber='$serialNumber' and fromCustomerId=$cid and deleted=0")->find();
				if($proInfo){
					Output::instance()->resultCode(1,"商品条码重复");
					return;
				}
			}
			$resultPro = $ProductModel->add($data);
			$id=$resultPro;
		}
		$inventoryCount=0;
		$seckillInventoryCount =0;
		if($supportSpecification == 1 && $speciData != NULL){
			if($pid<0){
				$specGroupModel->where("pid=$pid and fromCustomerId=$cid")->setField("pid",$id);
			}
			$specModel->where("pid={$id}")->delete();
			$speciData = json_decode($speciData);
			foreach($speciData as $key => $value){
				$inventoryCount+=$value->inventoryCount;
				$seckillInventoryCount+=$value->seckillInventoryCount;
				$addData['firstSpecificId'] = $value->firstid;
				$addData['firstSpecificName'] = $value->firstname;
				$addData['secSpecificId'] = $value->secondid;
				$addData['secSpecificName'] = $value->secondname;
				$addData['inventoryCount'] = $value->inventoryCount;
				$addData['firstSpecificUrl'] = $value->firstSpecificUrl;
				$addData['secSpecificUrl'] = $value->secSpecificUrl;
				$addData['serialNumber'] = $value->serialNumber;
				$addData['seckillPrice'] = $value->seckillPrice;
				$addData['seckillInventoryCount'] = $value->seckillInventoryCount;
				$addData['seckillSalce'] = $value->seckillSalce;
				if($addData['serialNumber']){
					$proSpecInfo =$specModel->alias("a")
					->join("inner join wx_module_product b on a.pid=b.id")
					->where("a.serialNumber='".$addData['serialNumber']."' and b.fromCustomerId=$cid and b.deleted=0 and b.supportSpecification=1")
					->find();
					if($proSpecInfo){
						Output::instance()->resultCode(1,"商品条码重复");
						$ProductModel->rollback();
						return;
					}
				}
				$addData['weight'] = $value->weight;
				$addData['fixedPrice'] = $value->fixedPrice;
				$addData['discountedPrice'] = $value->discountedPrice;
				$addData['supplyPrice'] = $value->supplyPrice;
				$addData['channelSupplyPrice'] = $value->channelSupplyPrice;
				$addData['platCut'] = $value->platCut;
				$addData['saleCut'] = $value->saleCut;
				$addData['miPrice'] = $value->miPrice;
				$addData['customsName'] = $value->customsName;
				$addData['tariff'] = $value->tariff;
				$addData['customsPrice'] = $value->customsPrice;
				$addData['supplierSkuNo'] = $value->supplierSkuNo;
                $addData['firstSpecificUnit'] = $value->firstSpecificUnit;
                $addData['secSpecificUnit'] = $value->secondSpecificUnit;
				$addData['pid'] = $id;
				$specModel->add($addData);
			}
			$data = null;
			$data['inventoryCount'] = $inventoryCount;
			$data['seckillInventoryCount'] = $seckillInventoryCount;
			$ProductModel->where("id=$id")->save($data);
		}
		//分享基础表
		$shareBaseData=array(
			"module" => "product" ,
			"moduleId" => $id ,
			"shareCount" => 0 ,
			"viewCount" => 0 ,
			"praiseCount" => 0 , 
			"commentCount" => 0 , 
			"createTime"=> $time,
			"tplId" => $startTplId,
			"delete" => 0 
		);
		//分享素材表
		$shareMaterData=array(
			"title" => $title ,
			"shareImg" => $shareImgs,
			"shareImg1" => $shareImgs1,
			"description" => $recommend
		);
		$shareBaseWhere["module"]="product";
		$shareBaseWhere["moduleId"]=$id;
		if($pid&&$pid>0) {
			$resultBase=$shareBaseModel->where($shareBaseWhere)->save($shareBaseData);
			//修改分享素材表
			$resultBaseList=$shareBaseModel->where($shareBaseWhere)->find();
			if($resultBaseList) {
				$baseId=$resultBaseList["id"];
				$resultMeter=$shareMaterModel->where('sId=' . $baseId)->save($shareMaterData);
			}
		} else {
			$resultBase=$shareBaseModel->add($shareBaseData);
			//添加素材表
			if($resultBase ) {
				$shareMaterData["sId"]=$resultBase;
				$resultMeter=$shareMaterModel->add($shareMaterData);
			}
		}
		Session::switchCustomer($cid);
		if ($resultPro) {
			$arrTag = explode(",", $tags);
			$ProductTagListModel->where("pid=$id")->delete();
			if($tags != ''){
				foreach ($arrTag as $tagId) {
					$dataTagList["tagId"] = $tagId;
					$dataTagList["pid"] = $id;
					$ProductTagListModel->add($dataTagList);
				}
			}
		}
		if ($channels) {
			$channels = explode(",", $channels);
			$supplyChainPro->where("pid=$id")->delete();
			if($channels != ''){
				foreach ($channels as $channel) {
					if(!$channel){continue;}
					$dataTagList["cId"] = $channel;
					$dataTagList["pid"] = $id;
					$supplyChainPro->add($dataTagList);
				}

			}
		}
		//添加或者修改商品的单位信息
        if ($unitInfo){
		    //首先删除之前表中所存储的单位信息
            $where_unit['cid'] = $cid;
            $where_unit['pid'] = $id;
            $productUnit->where($where_unit)->delete();
            //循环添加单位信息
            foreach($unitInfo as $key=>$value) {
                $save_unit['cid'] =$cid;
                $save_unit['pid'] =$id;
                $save_unit['unitName'] =$value['unitName'];
                $save_unit['isBasicUnit'] =$value['isBasicUnit'];
                $save_unit['unitConversion'] =$value['unitConversion'];
                $productUnit->save($save_unit);
            }
        }


		if($resultPro!==false && $resultBase!==false && $resultMeter!==false) {
			$ProductModel->commit();
			//清除保存在redis中的缓存
			self::cacheDel($id, $cid);
			Output::instance()->resultCode();
		} else {
			$ProductModel->rollback();
			Output::instance()->resultCode(code_sql_error);
		}
	}
	public function getTemplateList($type) {
		$tplModel = M("pb_template");
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$where["module"]=array('eq',$type);
		$arr = $tplModel->where($where)->select();
		if ($arr) {
			Output::instance()->objArray($arr);
		} else {
			Output::instance()->resultCode();
		}
	}
	public function getTemplateById($id) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$tempModel = M("pb_template");
		$res = $tempModel ->where("id=$id")->find();
		Session::switchCustomer($cid);
		if ($res!==false) {
			Output::instance()->object($res);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}
	public function getProductById($id,$cId=null) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cId?$cid=$cId:$cid = Session::$user["customerId"];
		$userId= session("id");
		Session::switchCustomer(0);
		$ProductModel = M("module_product");
		$TagListModel = M("module_product_tag_list");
		$spec = m('module_product_specification');
		$supplyChainPro = M("module_supply_chain_product");
		$customerUser = M("customer_user");
        $productUnit = M("module_product_unit");
		Session::switchCustomer($cid);
		$customerInfo = $customerUser->where("id=$userId")->field('supplyRelation,supplyChainId')->find();
		$materialKeyword = M("material");
		$condition["pro.id"] = array("eq",$id);
		$condition["s.module"] = array("eq",'product');
		$product = $ProductModel->alias("pro")->where($condition)
			->join('wx_product_type type ON type.id=pro.typeId')
			->join('wx_mivendor v ON v.id=pro.vId')
			->join('inner join wx_mishare s ON s.moduleId=pro.id')
			->join('inner join wx_mishare_material mm ON s.id=mm.sId')
			->join("wx_".$cid."_material b on pro.microId=b.id")
			->join('wx_'.$cid.'_module_distribution_scheme dis on pro.distributionId = dis.id')
			->join("wx_module_supply_chain_product e on pro.id=e.pid")
			->field('pro.*,type.name tname,v.name as vendorName,v.supplierModule,mm.shareImg,mm.shareImg1,s.tplId as startTplId,dis.name as distributionName,dis.id as distributionId,b.name as microName,group_concat(e.cId) as channels')
			->find();
		if ($product) {
				if($product['isChainPro']==1){//供应链商品
					$supplyProInfo = $ProductModel->alias("a")
						->join('wx_mivendor v ON v.id=a.vId')
						->where("a.id=".$product['supplyProId'])
						->field("a.*,v.name as vendorName")
						->find();
					$product['serialNumber']=$supplyProInfo['serialNumber'];
					$product['inventory']=$supplyProInfo['inventory'];
					$product['inventoryCount']=$supplyProInfo['inventoryCount'];
					$product['supplyPrice']=$supplyProInfo['supplyPrice'];
					$product['channelSupplyPrice']=$supplyProInfo['channelSupplyPrice'];
					$product['vendorName']=$supplyProInfo['vendorName'];
				}
				$json = json_decode($product["json"],true);
				$jsonName = array_keys($json);
				foreach($jsonName as $key=>$value){
					$product[$value]=$json[$value];
				}
				unset($product["json"]);
				$activityinfo = json_decode($product["activityinfo"],true);
				$activityname = array_keys($activityinfo);
				foreach($activityname as $key =>$value){
					$product[$value] = $activityinfo[$value];
				}
				unset($product["activityinfo"]);
				$pid = $product["id"];
				$arrTag = $TagListModel->alias("taglist")->where("pid=$pid")
					->join('wx_module_product_tag tag ON taglist.tagId=tag.id')
					->field("taglist.*,tag.id,GROUP_CONCAT(tag.id) as tagsId")->find();
				$product["tags"] = $arrTag["tagsId"];
				$materialName =$materialKeyword->where("id=".$product["freeBuyMaterialId"])->field("xml as materialComment")->find();
				$product["materialComment"] = $materialName["materialComment"];
					$where['pid'] = $id;
					$tmp = array(); 
					$specResult = $spec->where($where)->select();
					$temp = array();
					foreach($specResult as $key => $value){
						$supplyWhere=null;
						$supplyWhere['pid']=array('eq',$product['supplyProId']);
						$supplyWhere['firstSpecificName']=array('eq',$value['firstSpecificName']);
						$value['secSpecificName']?$supplyWhere['secSpecificName']=array('eq',$value['secSpecificName']):"";
						array_push($tmp, $value['firstSpecificId']);
						array_push($tmp, $value['secSpecificId']);
						$temp1 = array();
						$temp1['firstid'] = $value['firstSpecificId'];
						$temp1['secondid'] = $value['secSpecificId'];
						if($product['isChainPro']==1){
							$supplyProSpec = $spec->where($supplyWhere)->find();
							$temp1['count'] = $supplyProSpec['inventoryCount'];
							$temp1['serialNumber'] = $supplyProSpec['serialNumber'];
							$temp1['supplyPrice'] = $supplyProSpec['supplyPrice'];
							$temp1['channelSupplyPrice'] = $supplyProSpec['channelSupplyPrice'];
						}else{
							$temp1['count'] = $value['inventoryCount'];
							$temp1['serialNumber'] = $value['serialNumber'];
							$temp1['supplyPrice'] = $value['supplyPrice'];
							$temp1['channelSupplyPrice'] = $value['channelSupplyPrice'];
						}
						$temp1['weight'] = $value['weight'];
						$temp1['fixedPrice'] = $value['fixedPrice'];
						$temp1['discountedPrice'] = $value['discountedPrice'];
						$temp1['platCut'] = $value['platCut'];
						$temp1['saleCut'] = $value['saleCut'];
						$temp1['miPrice'] = $value['miPrice'];
						$temp1['seckillPrice'] = $value['seckillPrice'];
						$temp1['seckillInventoryCount'] = $value['seckillInventoryCount'];
						$temp1['seckillSalce'] = $value['seckillSalce'];
						$temp1['customsName'] = $value['customsName'];
						$temp1['tariff'] = $value['tariff'];
						$temp1['customsPrice'] = $value['customsPrice'];
						$temp1['supplierSkuNo'] = $value['supplierSkuNo'];
						array_push($temp, $temp1);
					}

					$tmp = array_flip(array_flip($tmp));
					foreach($tmp as $k=>$v){
						if ($v == "0") unset($tmp[$k]);
					}
					$product['specAttr'] = implode(',',$tmp);
					
					$product['specCount'] = json_encode($temp);
			$product['supplyRelation'] = $customerInfo['supplyRelation'];
			$product['supplyChainId'] = $customerInfo['supplyChainId'];

			//获取商品的单位信息
            $where_unit['cid'] = $cid ;
            $where_unit['pid'] = $id;
            $unitInfo = $productUnit->where($where_unit)->select();
            $unitInfo = empty($unitInfo) ? []: $unitInfo;
            $product['unitInfo'] = $unitInfo;
			Output::instance()->object($product);
		} else {
			Output::instance()->resultCode(code_success);
		}
	}
	
	public function deleteProduct($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		
		$ProductModel = M("module_product");
		$ShareModel = M("mishare");
		$MaterialModel = M("mishare_material");
		$McommentModel = M("mirecomment");
		
		$customerUser = m('customer_user');

		$idArray = explode(",",$id);
		
		if($id){
			$delWhere['id'] = array('in', $id);
			$ProductModel->startTrans();
			$result = $ProductModel->where($delWhere)->setField("deleted", 1);
			Session::switchCustomer($cid);
			if ($result) {
				$sharewhere['module'] = 'product';
				$sharewhere['moduleId'] = $id;
				$shareId = $ShareModel->where($sharewhere)->find();
				Log::write("shareId:" . $ShareModel->getlastSql());
				$mwhere['sId'] = $shareId['id'];
				$result = $ShareModel->where($sharewhere)->delete();
				Log::write("删除share:$result ". $ShareModel->getlastSql());
				if ($result === false) {
					$ProductModel->rollback();
					Output::instance()->resultCode(code_sql_error);
					return false;
				}
				$result = $MaterialModel->where($mwhere)->delete();
				Log::write("删除Material:$result ". $MaterialModel->getlastSql());
				if ($result === false) {
					$ProductModel->rollback();
					Output::instance()->resultCode(code_sql_error);
					return false;
				}
				$result = $McommentModel->where($mwhere)->delete();
				Log::write("删除comment:$result ". $McommentModel->getlastSql());
				if ($result === false) {
					$ProductModel->rollback();
					Output::instance()->resultCode(code_sql_error);
					return false;
				}else{
					$ProductModel->commit();
					Output::instance()->resultCode(code_success);
					R('Log/add', array(module_handle_product, $id, op_delete, $pdt["name"]));
				}

			} else {
				Output::instance()->resultCode(code_sql_error);
			}
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}
	/*
	 * 产品上下架接口
	 * $isRemove：true下架，false上架
	 */
	public function  removeProduct($ids, $isRemove){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$ProductModel  = M('module_product');
		$cUser = m('customer_user');
		$data['isRemoved'] = $isRemove;
		$idArray = explode(',', $ids);
		if (count($idArray) > 1) {
			$whereArray = array();
			foreach ($idArray as $id) { 
				array_push($whereArray, array('eq', intval($id)));
			}
			array_push($whereArray, 'OR');
			$where["id"] = $whereArray;
		} else {
			$where["id"] = $ids;
		}
		
		
		$result = $ProductModel->where($where)->save($data);
		Session::switchCustomer($cid);
		if ($result !== false) {
			Output::instance()->resultCode();
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}
	/**
	 * 获取类目一级列表
	 * 
	 * @param: string $session_id 
	 * @return: array $result 一级类目列表
	 */
	public function getTypeOneList(){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$typeModel = m('product_type');
		Session::switchCustomer($cid);
		$where['parentId'] = 0;
		
		$result = $typeModel->where($where)->select();
		
		if($result){
			Output::instance()->objArray($result);
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}
	public function addProductSalesCount($oid) {
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$ProductModel = new Model();

		Log::write("add pro oid is " . $oid);
		$addStr = "=$oid";
		$productList = $ProductModel->table("wx_module_product_order_detail")
			->where("oid in ($oid)")
			->field("count as counts,pid")
			->select();
		foreach($productList as $key=>$value){
			$ProductModel->table("wx_module_product")->where("id=".$value['pid'])->setInc("salesCount",$value['counts']);
		}
		// add sales count
//		$sqlSalesCount = "UPDATE wx_module_product INNER JOIN wx_module_product_order_detail ON wx_module_product.id = "
//		. " wx_module_product_order_detail.pid SET wx_module_product.salesCount = "
//		. " wx_module_product.salesCount + wx_module_product_order_detail.count WHERE "
//		. " wx_module_product_order_detail.oid in ($oid)";

		Session::switchCustomer($cid);
//		$ProductModel->query($sqlSalesCount);
	}
    
    public function deductProductSalesCount($oid) {
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $ProductModel = new Model();
        
        $addStr = "=$oid";
        $productList = $ProductModel->table("wx_module_product_order_detail")
            ->where("oid in ($oid)")
            ->field("count as counts,pid")
            ->select();
        foreach($productList as $key=>$value){
            $ProductModel->table("wx_module_product")->where("id=".$value['pid'])->setDec("salesCount",$value['counts']);
        }
        Session::switchCustomer($cid);
    }
    
    
	public function deductProductInventory($oid) {
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$DetailModel = M("module_product_order_detail");
		$orderModel = M("module_product_order");
		$idArray = explode(',', $oid);
		if (count($idArray) > 1) {
			$whereArray = array();
			foreach ($idArray as $id) {
				array_push($whereArray, array('eq', intval($id)));
			}
			array_push($whereArray, 'OR');
			$whereDetail["oid"] = $whereArray;
		} else {
			$whereDetail["oid"] = $oid;
		}
		
		$orderDetailArr = $DetailModel->alias("detail")
			->field("detail.id as did, detail.count, detail.oid,detail.playType as dPlayType,pdt. *")
			->join("wx_module_product pdt ON detail.pid = pdt.id")
			->where($whereDetail)->select();
		$ProductModel = new Model();
		if ($orderDetailArr) {
			foreach ($orderDetailArr as $orderDetail) {
				$whereOrder["dt.id"] = $orderDetail["did"];
				$specDetail = $DetailModel->alias("dt")
					->join("RIGHT JOIN wx_module_product_order_detail_specification spec ON spec.did = dt.id")
					->where($whereOrder)->select();
				if($orderDetail['isChainPro']){
					$detailPid = $orderDetail["supplyProId"];
				}else{
					$detailPid = $orderDetail["id"];
				}
				if ($specDetail) {
					$firstSpecificName = $specDetail[0]["firstSpecificName"];
					$secSpecificName = $specDetail[0]["secSpecificName"];
					$count = $orderDetail["count"];
					if($orderDetail["playType"]=="4"&&$orderDetail['dPlayType']='seckillPrice'){
						$sqlInventory = "UPDATE wx_module_product_specification spec  JOIN wx_"
							."module_product ON wx_module_product.id = spec.pid "
							."SET spec.seckillInventoryCount = spec.seckillInventoryCount - $count "
							."WHERE spec.pid= ".$orderDetail["id"]
							." AND spec.firstSpecificName='$firstSpecificName' AND spec.secSpecificName='$secSpecificName' ";
						$ProductModel->query($sqlInventory);
						$sqlInventory = "UPDATE wx_module_product_specification spec  JOIN wx_"
							."module_product ON wx_module_product.id = spec.pid "
							."SET spec.inventoryCount = spec.inventoryCount - $count"
							."WHERE spec.pid=$detailPid "
							."AND spec.firstSpecificName='$firstSpecificName' AND spec.secSpecificName='$secSpecificName' "
							."AND wx_module_product.inventory = 1";
						$ProductModel->query($sqlInventory);
					}else{
						$sqlInventory = "UPDATE wx_module_product_specification spec  JOIN wx_"
							."module_product ON wx_module_product.id = spec.pid "
							."SET spec.inventoryCount = spec.inventoryCount - $count "
							."WHERE spec.pid=$detailPid "
							."AND spec.firstSpecificName='$firstSpecificName' AND spec.secSpecificName='$secSpecificName' "
							."AND wx_module_product.inventory = 1";
					}
					$ProductModel->query($sqlInventory);
				}
//				$detailId=$orderDetail["did"];
				$detailCount = $orderDetail['count'];
				if($orderDetail["playType"]=="3"){
					$sqlInventory ="UPDATE wx_module_product set inventoryCount=inventoryCount-1 where id=$detailPid and inventory=1";
//					$sqlInventory = "UPDATE wx_module_product INNER JOIN wx_module_product_order_detail ON wx_module_product.id = wx_module_product_order_detail.pid "
//						."SET wx_module_product.inventoryCount = wx_module_product.inventoryCount - 1 "
//						."WHERE wx_module_product_order_detail.id = {$detailId} AND wx_module_product.inventory=1";
				}else{
					if($orderDetail["playType"]=="4"&&$orderDetail['dPlayType']='seckillPrice'){
						$sqlInventory ="UPDATE wx_module_product set seckillInventoryCount=seckillInventoryCount-$detailCount where id=".$orderDetail["id"];
						$ProductModel->query($sqlInventory);
						$sqlInventory ="UPDATE wx_module_product set inventoryCount=inventoryCount-$detailCount where id=$detailPid and inventory=1";
					}else{
						$sqlInventory ="UPDATE wx_module_product set inventoryCount=inventoryCount-$detailCount where id=$detailPid and inventory=1";
					}
//					$sqlInventory = "UPDATE wx_module_product INNER JOIN wx_module_product_order_detail ON wx_module_product.id = wx_module_product_order_detail.pid "
//						."SET wx_module_product.inventoryCount = wx_module_product.inventoryCount - wx_module_product_order_detail.count "
//						."WHERE wx_module_product_order_detail.id = {$detailId} AND wx_module_product.inventory=1";
				}
				$ProductModel->query($sqlInventory);
				Session::switchCustomer($cid);
			}
		} else {
			Session::switchCustomer($cid);
			Log::write('[Product - deductProductInventory] deduct inventory none');
		}
	}
    
    public function revertProductInventory($oid) {
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $DetailModel = M("module_product_order_detail");
        $idArray = explode(',', $oid);
        if (count($idArray) > 1) {
            $whereArray = array();
            foreach ($idArray as $id) {
                array_push($whereArray, array('eq', intval($id)));
            }
            array_push($whereArray, 'OR');
            $whereDetail["oid"] = $whereArray;
        } else {
            $whereDetail["oid"] = $oid;
        }
        
        $orderDetailArr = $DetailModel->alias("detail")
        ->field("detail.id as did, detail.count, detail.oid,detail.playType as dPlayType, pdt. *")
        ->join("wx_module_product pdt ON detail.pid = pdt.id")
        ->where($whereDetail)->select();
        
        $ProductModel = new Model();
        if ($orderDetailArr) {
            foreach ($orderDetailArr as $orderDetail) {
                
                $whereOrder["dt.id"] = $orderDetail["did"];
                $specDetail = $DetailModel->alias("dt")
                ->join("RIGHT JOIN wx_module_product_order_detail_specification spec ON spec.did = dt.id")
                ->where($whereOrder)->select();
				if($orderDetail['isChainPro']){
					$detailPid = $orderDetail["supplyProId"];
				}else{
					$detailPid = $orderDetail["id"];
				}
                if ($specDetail) {

					$firstSpecificName = $specDetail[0]["firstSpecificName"];
					$secSpecificName = $specDetail[0]["secSpecificName"];
					$count = $orderDetail["count"];
					if($orderDetail["playType"]=="4"&&$orderDetail['dPlayType']='seckillPrice'){
						$sqlInventory = "UPDATE wx_module_product_specification spec  JOIN wx_"
							."module_product ON wx_module_product.id = spec.pid "
							."SET spec.seckillInventoryCount = spec.seckillInventoryCount + $count WHERE spec.pid=".$orderDetail["supplyProId"]
							." AND spec.firstSpecificName='$firstSpecificName' AND spec.secSpecificName='$secSpecificName' ";
						$ProductModel->query($sqlInventory);
						$sqlInventory = "UPDATE wx_module_product_specification spec  JOIN wx_"
							."module_product ON wx_module_product.id = spec.pid "
							."SET spec.inventoryCount = spec.inventoryCount + $count WHERE spec.pid=$detailPid "
							."AND spec.firstSpecificName='$firstSpecificName' AND spec.secSpecificName='$secSpecificName' "
							."AND wx_module_product.inventory = 1";
						$ProductModel->query($sqlInventory);
					}else{
						$sqlInventory = "UPDATE wx_module_product_specification spec  JOIN wx_"
							."module_product ON wx_module_product.id = spec.pid "
							."SET spec.inventoryCount = spec.inventoryCount + $count WHERE spec.pid=$detailPid "
							."AND spec.firstSpecificName='$firstSpecificName' AND spec.secSpecificName='$secSpecificName' "
							."AND wx_module_product.inventory = 1";
						$ProductModel->query($sqlInventory);
					}
                }

//				$detailId=$orderDetail["did"];
				$detailCount = $orderDetail['count'];
                // 通用产品扣减库存
				if($orderDetail["playType"]=="3"){
					$sqlInventory ="UPDATE wx_module_product set inventoryCount=inventoryCount+1 where id=$detailPid and inventory=1";
//					$sqlInventory = "UPDATE wx_module_product INNER JOIN wx_module_product_order_detail ON wx_module_product.id = wx_module_product_order_detail.pid "
//					."SET wx_module_product.inventoryCount = wx_module_product.inventoryCount + 1 "
//					."WHERE wx_module_product_order_detail.id = {$detailId} AND wx _module_product.inventory=1";
				}else{
					if($orderDetail["playType"]=="4"&&$orderDetail['dPlayType']='seckillPrice'){
						$sqlInventory ="UPDATE wx_module_product set seckillInventoryCount=seckillInventoryCount+$detailCount where id=".$orderDetail["supplyProId"];
						$ProductModel->query($sqlInventory);
						$sqlInventory ="UPDATE wx_module_product set inventoryCount=inventoryCount+$detailCount where id=$detailPid and inventory=1";
					}else{
						$sqlInventory ="UPDATE wx_module_product set inventoryCount=inventoryCount+$detailCount where id=$detailPid and inventory=1";
					}
//					$sqlInventory = "UPDATE wx_module_product INNER JOIN wx_module_product_order_detail ON wx_module_product.id = wx_module_product_order_detail.pid "
//					."SET wx_module_product.inventoryCount = wx_module_product.inventoryCount + wx_module_product_order_detail.count "
//					."WHERE wx_module_product_order_detail.id = {$detailId} AND wx_module_product.inventory=1";
				}
                $ProductModel->query($sqlInventory);
                Session::switchCustomer($cid);
            }
        } else {
            Session::switchCustomer($cid);
            Log::write('[Product - deductProductInventory] deduct inventory none');
        }
    }
    
	public function getOrderStatusName($status) {
		$statusName = '';
		switch($status) {
			case order_status_delivered:
				$statusName = ORDER_STATUS_DELIVERED_TEXT;
				break;
			case order_status_deliveredtostore:
				$statusName = ORDER_STATUS_DELIVEREDTOSTORE_TEXT;
				break;
			case order_status_delivering:
				$statusName = ORDER_STATUS_DELIVERING_TEXT;
				break;
			case order_status_deliveringtostore:
				$statusName = ORDER_STATUS_DELIVEREDTOSTORE_TEXT;
				break;
			case order_status_ok:
				$statusName = ORDER_STATUS_OK_TEXT;
				break;
			case ORDER_STATUS_PAYING:
				$statusName = ORDER_STATUS_PAYING_TEXT;
				break;
			case order_status_payingconfirm:
				$statusName = ORDER_STATUS_PAYINGCONFIRM_TEXT;
				break;
			case order_status_refund:
				$statusName = ORDER_STATUS_REFUND_TEXT;
				break;
			case ORDER_STATUS_REFUNDEDPART:
				$statusName = ORDER_STATUS_REFUNDEDPART_TEXT;
				break;
			case ORDER_STATUS_REFUNDING:
				$statusName = ORDER_STATUS_REFUNDING_TEXT;
				break;
			default:
				$statusName = '状态错误';
				break;
		}
		return $statusName;
	}
	public function getOrderPayTypeName($payType) {
		$payTypeName = '';
		switch($payType) {
			case ORDER_PAYTYPE_WXPAY:
				$payTypeName = ORDER_PAYTYPE_WXPAY_TEXT;
				break;
			case ORDER_PAYTYPE_DELIVERIY_PAY:
				$payTypeName = ORDER_PAYTYPE_DELIVERIY_PAY_TEXT;
				break;
			case ORDER_PAYTYPE_STORED_PAY:
				$payTypeName = ORDER_PAYTYPE_STORED_PAY_TEXT;
				break;
			case ORDER_PAYTYPE_TRANSFER:
				$payTypeName = ORDER_PAYTYPE_TRANSFER_TEXT;
				break;
			case ORDER_PAYTYPE_UPAY:
				$payTypeName = ORDER_PAYTYPE_UPAY_TEXT;
				break;
			case ORDER_PAYTYPE_INTERACT:
				$payTypeName = ORDER_PAYTYPE_INTERACT_TEXT;
				break;
			case ORDER_PAYTYPE_CONSUME:
				$payTypeName = ORDER_PAYTYPE_CONSUME_TEXT;
				break;
            case ORDER_PAYTYPE_TENPAY:
                $payTypeName = ORDER_PAYTYPE_TENPAY_TEXT;
                break;
			default:
				$payTypeName = '支付方式错误';
				break;
		}
		return $payTypeName;
	}
	
	public function getOrderDelieveryTypeName ($deliveryType) {
		$deliveryTypeName = '';
		switch($deliveryType) {
			case ORDER_DELIVERYTYPE_PICKUP:
				$deliveryTypeName = ORDER_DELIVERYTYPE_PICKUP_TEXT;
				break;
			case ORDER_DELIVERYTYPE_DELIVERY:
				$deliveryTypeName = ORDER_DELIVERYTYPE_DELIVERY_TEXT;
				break;
			default:
				$deliveryTypeName = '配送方式错误';
				break;
		}
		return $deliveryTypeName;
	}
	/**
	 * 根据父ID查找对应的子类列表.
	 * 
	 * @param string $session_id 
	 * @param int $parentId 父id
	 * @return array 对应的子类列表.
	 */
	public function getTypeListByParentId($parentId){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		if(!$parentId){
			return;
		}
		
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$typeModel = m('product_type');
		Session::switchCustomer($cid);
		$where['parentId'] = $parentId;
		
		$result = $typeModel->where($where)->select();
		
		if($result){
			Output::instance()->objArray($result);
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}
	
	

	/**
	 * 根据id获取对应的类目名称
	 * 
	 * @param string $session_id
	 * @param int $id 类目ID
	 * 
	 * @return String $name 类目名称
	 */
	public function getTypeNameById($id){
		
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		if(!$id){
			return;
		}
		
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$typeModel = m('product_type');
		$where['id']= $id;
		$name = $typeModel->where($where)->getField('name');
		
		return $name;
// 		if($name){
// 			Output::instance()->object($name);
// 		}else{
// 			Output::instance()->resultCode(code_sql_error);
// 		}
	}
	
	public function getTypeList($dependence) {
		$ProductTypeModel = M("module_type");
		
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$condition["dependence"] = array('eq',$dependence);
		$arr = $ProductTypeModel->where($condition)->select();
		if ($arr) {
			Output::instance()->objArray($arr);
		} else {
			Output::instance()->resultCode(code_success);
		}
	}
	public function addTag($tagName,$title='',$number=0,$picUrl='',$description='',$groupId=null){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$productTagGroup = M("module_product_tag_group");
		$ProductTagModel = M("module_product_tag");
		$where['name'] = $tagName;
		$where['fromCustomerId'] = $cid;
		$count = $ProductTagModel->where($where)->count();
		if($count > 0 ){
			Output::instance()->resultCode(code_product_add_tag_exist);
			return;
		}
		if(!$groupId){
			$groupId=$productTagGroup->where("groupName='默认' and cId=$cid")->field("id")->find();
			$groupId= $groupId['id'];
		}
		if(!$groupId){
			$data['groupName']='默认';
			$data['deleted']=0;
			$data['cId']=$cid;
			$data['createTime']=date("Y-m-d H:i:s");
			$groupId = $productTagGroup->add($data);
		}
		$add['name'] = $tagName;
		$add['number']=$number;
		$add['picUrl']=$picUrl;
		$add['description']=$description;
		$add['title']=$title;
		$add['fromCustomerId']=$cid;
		$add['groupId']=$groupId;
		$addTag = $ProductTagModel->add($add);
		Session::switchCustomer($cid);
		if ($addTag) {
			$out=new StdClass();
			$out->code=0;
			$out->id=$addTag;
			$out->groupId=$groupId;
			Output::instance()->object($out);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
		
	}
	//展示分类分组列表
	public function getTagGroupList($tagName='',$start=0,$limit=10){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$productTagGroup = M("module_product_tag_group");
		Session::switchCustomer($cid);
		$where['cId']=array('eq',$cid);
		$where['deleted']=array('eq',0);
		$tagName?$where['groupName']=array('like',"%$tagName%"):"";
		$arr = $productTagGroup->where($where)->limit($start,$limit)->order("createTime desc")->select();
		if($arr){
			$count = $productTagGroup->where($where)->count();
			Output::instance()->objArray($arr,$count);
		}else{
			Output::instance()->resultCode();
		}
	}
	//删除展示分类分组
	public function delTagGroup($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$productTagGroup = M("module_product_tag_group");
		$productTag = M("module_product_tag");
		Session::switchCustomer($cid);
		$data['deleted']=1;
		$where['id']=array("eq",$id);
		$result = $productTagGroup->where($where)->save($data);
		$groupId=$productTagGroup->where("groupName='默认' and cId=$cid")->field("id")->find();
		$groupId=$groupId['id'];
		if(!$groupId){
			$data['groupName']='默认';
			$data['deleted']=0;
			$data['cId']=$cid;
			$data['createTime']=date("Y-m-d H:i:s");
			$groupId = $productTagGroup->add($data);
		}
		$productTag->where("groupId=$id")->setField("groupId",$groupId);
		if($result!==false){
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}
	//查看展示分类分组设置
	public function getTagGroup($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$productTagGroup = M("module_product_tag_group");
		Session::switchCustomer($cid);
		$where['id']=array("eq",$id);
		$result = $productTagGroup->where($where)->find();
		Output::instance()->object($result);
	}
	//添加展示分类分组
	public function addTagGroup($groupName,$id=null){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$productTagGroup = M("module_product_tag_group");
		Session::switchCustomer($cid);
		$data['groupName']=$groupName;
		if($id){
			$result = $productTagGroup->where("id=$id")->save($data);
			if($result!==false){
				Output::instance()->resultCode();
				return;
			}
		}else{
			$data['deleted']=0;
			$data['cId']=$cid;
			$data['createTime']=date("Y-m-d H:i:s");
			$result = $productTagGroup->add($data);
			if($result){
				Output::instance()->resultCode();
				return;
			}
		}
		Output::instance()->resultCode(code_sql_error);
	}
	public function getTagAll($order="name", $orderBy="asc"){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$ProductTagModel = M("module_product_tag");
		$productTagGroup = M("module_product_tag_group");
		$where['fromCustomerId'] =array('eq', $cid);
		$groupWhere['cId']=array("eq",$cid);
		$groupWhere['deleted']=array("eq",0);
		$arr = $productTagGroup->where($groupWhere)->order("createTime desc")->field("id,groupName")->select();
		foreach($arr as $key=>$value){
			$where['groupId']=array("eq",$value['id']);
			$arr[$key]['tagList']=$ProductTagModel->where($where)->order("$order $orderBy")->select();
		}
		Session::switchCustomer($cid);
		if ($arr) {
			$count =  $ProductTagModel->count();
			Output::instance()->objArray($arr, $count);
		} else {
			Output::instance()->resultCode(code_success);
		}
		
	}
	
	
	public function getTag($order="a.name", $orderBy="asc", $start = 0, $limit = 25,$tagName='',$isExport = false,$cid=NULL) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		if(!$cid){
			$cid = Session::$user['customerId'];
		}
		Session::switchCustomer(0);
		$ProductTagModel = M("module_product_tag");
		Session::switchCustomer($cid);
		$where = '';
		if($tagName!=''){
			$where['a.name'] = array('like','%'.$tagName.'%');
		}
		$where['a.fromCustomerId'] = array('eq',$cid);
		if (!$isExport) {
			$arr = $ProductTagModel->alias("a")
				->join("wx_module_product_tag_group b on a.groupId=b.id")
				->join("wx_".$cid."_share_statistics sta on a.id=sta.moduleId and sta.module='getProductByTagId'")
				->where($where)
				->field("a.*,sta.uv,b.groupName")
				->order("$order $orderBy")
				->limit("$start, $limit")->select();
			if ($arr) {
				$count =  $ProductTagModel->alias("a")->where($where)->count();
				Output::instance()->objArray($arr, $count);
			} else {
				Output::instance()->resultCode(code_success);
			}
		}else{
			$arr = $ProductTagModel->where($where)->order("$order $orderBy")->select();
			$expCellName  = array(
				array('number','分类编号'),
				array('name','分类名称'),
				array('picUrl','分类图片'),
				array('description','分类描述'),
			);
			Output::instance()->objArrayExcel('商品展示分类', $expCellName, $arr);
		}
	}
	
	public function getTagById($id,$phone=false){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$ProductTagModel = M("module_product_tag");
		Session::switchCustomer($cid);
// 		$cid = Session::$user["customerId"];
// 		$condition["fromCustomerId"] = array('eq',$cid);
		$condition["a.id"] = array('eq',$id);
		
		$tag = $ProductTagModel->alias("a")
			->join("left join wx_module_product_tag_group b on a.groupId=b.id")
			->field("a.*,b.groupName,b.id as groupId")
			->where($condition)->find();
		if($phone){
			return $tag;
		}else{
			if ($tag) {
				Output::instance()->object($tag);
			} else {
				Output::instance()->resultCode(code_success);
			}
		}		
	}
	
	public function updateProductTag($id, $tagName,$title, $number, $picUrl, $description,$groupId) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$ProductTagModel = M("module_product_tag");
		
		$data["name"] = $tagName;
		$data["number"]= $number;
		$data["picUrl"] = $picUrl;
		$data['title']=$title;
		$data['groupId']=$groupId;
		$data["description"] = $description;
		$result = $ProductTagModel->where("id=$id")->save($data);
		if ($result !== false) {
			$data["id"] = $id;
			Output::instance()->object($data);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
		
	}
	
	public function deleteProductTag($id) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$ProductTagModel = M("module_product_tag");
		$result = $ProductTagModel->where("id=$id")->delete();
		if ($result) {
			Output::instance()->resultCode(code_success);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

	/**
	 * 更具类目ID获取多规格组列表
	 * @param int $typeId 类目ID
	 */
	public function getUnitType($pid,$cid=null){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$cid?"":$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$group = m('module_product_specification_group');
		$name = m('module_product_specification_name');
		
		$where['pid'] = $pid;
		$where['fromCustomerId'] = $cid;
		
		$result = $group->where($where)->field("id, groupName,spetype,specificUnit")->order("id")->select();
		$return = array();
		$return['list'] = array();
		$temp = array();
		foreach($result as $key=>$value){
			$tmp['id'] = $value['id'];
			$tmp['name'] = $value['groupName'];
			$tmp['spetype'] = $value['spetype'];
			$tmp['specificUnit'] = $value['specificUnit'];
			$tmpWhere['groupId'] = $value['id'];
			$tmpResult = $name->where($tmpWhere)->field("`id`, `specificationName` As `name`,`specificationUrl`")->order("id")->select();
// 			echo $name->getLastSql()."<br/>";
			$sublist = array();
			foreach($tmpResult as $k => $v){
				
				$tmpArray['id'] = $v['id'];
				$tmpArray['name'] = $v['name'];
				$tmpArray['specificationUrl'] = $v['specificationUrl'];
				array_push($sublist,$tmpArray);
			}
			
			$tmp['sublist'] = $sublist;
			array_push($temp, $tmp);
		}
		$return['list'] = $temp;
		Session::switchCustomer($cid);
		if($result){
			Output::instance()->object($return);
		}else{
			$return['list'] = [];
			Output::instance()->object($return);
		}

	}
	/**
	 * 添加规格, 删除规格.
	 * 
	 * @param  $data
	 */
	public function addUnitType($data){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$data = json_decode($data);
		$unitGroupId = $data->id;
		$unitGroupName = trim($data->name);
		$unitSubList = $data->subList;
		$typeId = $data->typeId;
		$spetype = $data->spetype;
		$specificUnit = $data->specificUnit;
		$pid = $data->pid;
		$method = $data->method;
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		if(!$pid){
			Output::instance()->resultCode(code_product_specification_group_typeid_not_exist);
			return;
		}
		$specModel = m('module_product_specification_group');
		$unitName = m('module_product_specification_name');
		$add['groupName'] = $unitGroupName;
		$add['fromCustomerId'] = $cid;
		$add['updateTime'] = date('Y-m-d H:i:s',time());
		$add['specificUnit'] = $specificUnit;
//		$add['typeId'] = $typeId;
		$add['pid'] = $pid;
		$add['spetype'] = $spetype;
		$update = null;
		if($unitGroupId == "") {
			$where['groupName'] = $unitGroupName;
			$where['pid']=$pid;
			$where['fromCustomerId']=$cid;
			//判断规格组是否已存在;
			$check = $specModel->where($where)->find();
			if($method == "add"){
				if($check){
					$groupId = $check['id'];
					$listCount = count($unitSubList);
					if($groupId > 0 && $listCount > 0){
						$addName['groupId'] = $groupId;
							
						foreach($unitSubList as $key => $value){
							if($value->id == ""){
								$addName['specificationName'] = trim($value->name);
								if (trim($value->specificationUrl)) {
									$addName['specificationUrl'] = trim($value->specificationUrl);
								}
								$addName['updateTime'] = date('Y-m-d H:i:s', time());
								$update = $unitName->add($addName);
							}else{
								$delName['id'] = $value->id;
								$update = $unitName->delete();
							}
						}
						Session::switchCustomer($cid);
						Output::instance()->resultCode();
							
					}else{
						Session::switchCustomer($cid);
						Output::instance()->resultCode(code_sql_error);
					}
				}else{
					$groupId = $specModel->add($add);
					$listCount = count($unitSubList);
					if($groupId > 0 && $listCount > 0){
						$addName['groupId'] = $groupId;
						foreach($unitSubList as $key => $value){
							if($value->id == ""){
								if (trim($value->specificationUrl)) {
									$addName['specificationUrl'] = trim($value->specificationUrl);
								}
								$addName['specificationName'] = trim($value->name);
								$addName['updateTime'] = date('Y-m-d H:i:s', time());
								$update = $unitName->add($addName);
							}else{
								$delName['id'] = $value->id;
								$update = $unitName->delete();
							}
						}
						Session::switchCustomer($cid);
						Output::instance()->resultCode();
							
					}else{
						Session::switchCustomer($cid);
						Output::instance()->resultCode(code_sql_error);
					}
				}
			}else if($method=="del"){
				$where['groupId'] = $check['id'];

				
				
				foreach($unitSubList as $key => $value){
					$where['id'] = $value->id;
					$update = $unitName->where($where)->delete();
					
					
				}
				Session::switchCustomer($cid);
				Output::instance()->resultCode();
			}
		}else{
			if(count($unitSubList) == 0){
				$editGroupWhere['id'] = $unitGroupId;
				$editData['groupName'] = $unitGroupName;
				$editData['spetype'] = $spetype;
				$update = $specModel->where($editGroupWhere)->save($editData);
			}else{
				foreach($unitSubList as $k => $v){
					
					if($v->id){
						$cid = Session::$user['customerId'];
						Session::switchCustomer(0);
						$supSpec = m('supplier_product_specification');
						Session::switchCustomer($cid);
						$editSpecWhere['id'] = $v->id;
						$update = $unitName->where($editSpecWhere)->delete();
						$supSpec->where("`firstSpecificId` = {$v->id} Or `secSpecificId` = {$v->id}")->delete();
					}else{
						$updateSpecData['groupId'] = $unitGroupId;
						$updateSpecData['specificationName'] = trim($v->name);
						if (trim($v->specificationUrl)) {
							$updateSpecData['specificationUrl'] = trim($v->specificationUrl);
						}
						$update = $unitName->add($updateSpecData);
					}
					
				}
				$editGroupWhere['id'] = $unitGroupId;
				$editData['groupName'] = $unitGroupName;
				$editData['spetype'] = $spetype;
				$update = $specModel->where($editGroupWhere)->save($editData);
			}
			if($update!==NULL){
				Session::switchCustomer($cid);
				Output::instance()->resultCode();
			}else{
				Session::switchCustomer($cid);
				Output::instance()->resultCode(code_sql_error);
			}
		}
	}
	
	/**
	 * 删除规格组 及对应的规格
	 * @param int $specGroupId 规格组ID
	 */
	public function delSpec($specGroupId){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$group = m('module_product_specification_group');
		$name = m('module_product_specification_name');
		
		$where['groupId'] = $specGroupId;
		$delName = $name->where($where)->delete();
		$del['id'] = $specGroupId;
		$delGroup = $group->where($del)->delete();
		
// 		Log::write("删除规格组:".$group->getLastSql().",删除规格:".$name->getLastSql());
		$cid = Session::$user['customerId'];
		Session::switchCustomer($cid);
		if($delGroup){
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}
	
	/**
	 * ihziluoh  微商城 添加 start
	 * 
	 */
	
	

	//加载所有的商品标签
	public function  getProductTagList(){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$TagModel = M("module_product_tag");
		Session::switchCustomer($cid);
//ihziluoh 添加CustomerId条件
		$where["m.fromCustomerId"] = $cid;
		$TagtModelArr = $TagModel->alias("m")
		->field("m.id,m.name,m.picUrl,m.description")
		->where($where)
		->select();
		if($TagtModelArr){
			$TagtModelArrExt = array();
			foreach ($TagtModelArr as $entity){
				$count = $this->getProductNum($cid,$entity["id"]);
			//	$count = $count > MAX_TAG_DISPLAY_COUNT ? MAX_TAG_DISPLAY_COUNT: $count;
				$entity["product_count"] = $count;
				array_push($TagtModelArrExt, $entity);
			}
			Output::instance()->objArray($TagtModelArrExt);
		}else{
			Output::instance()->resultCode(code_success);
		}
	}
	
	//获取产品数量
		public function getProductNum($cid,$tagId){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$cid = Session::$user["customerId"];
			Session::switchCustomer(0);
			$TagListModel = M("module_product_tag_list");
			Session::switchCustomer($cid);
			$where["mptl.tagId"] = $tagId;
			$where["p.isRemoved"] = 0;
			$where["p.deleted"] = 0;
			//ihziluoh 添加CustomerId条件
			$where["p.fromCustomerId"] = $cid;
			$count = $TagListModel->alias("mptl")
				->join("wx_module_product p ON p.id =mptl.pid ")
				->where($where)->count();
			return $count;
		}
		
	
	
	//获取标签下的产品数量
	public function getProductNumByTagId($tagId,$limit=null){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
// 		$count = $this->getProductNum($cid,$tagId);
// 		$count = $count>MAX_TAG_DISPLAY_COUNT ? MAX_TAG_DISPLAY_COUNT: $count;
// 		if($count){
		$tagId=explode(',',$tagId);
		$limit=explode(",",$limit);
		$i = 0;
		foreach ($tagId as $k => $v) {
		//ihziluoh 更改分表
			Session::switchCustomer(0);
			$ModuleProduct = M("module_product");
			Session::switchCustomer($cid);
			//$limitTemp = ($limitArr[$i] > MAX_TAG_DISPLAY_COUNT || empty($limitArr[$i]))
			//	? MAX_TAG_DISPLAY_COUNT : $limitArr[$i];
			//ihziluoh 添加CustomerId条件
			$where["mp.fromCustomerId"] = $cid;
			$where['mptl.tagId'] = $v;
			$where['mp.isRemoved'] = 0;
			$where['mp.deleted'] = 0;
			if($limit[$k]){
				$ModuleProductArr[] = $ModuleProduct->alias("mp")
					//ihziluoh 更改分表
					//	->join("wx_".$cid."_module_product_tag_list mptl ON mptl.pid =mp.id ")
					->join("wx_module_product_tag_list mptl ON mptl.pid =mp.id ")
					->join("wx_module_product_tag tag on mptl.tagId=tag.id")
					->field("mp.id,mp.name,mp.discountedPrice,mp.fixedPrice,mp.picUrl,tag.picUrl as tagPicUrl")
					->where($where)
					->limit(0,$limit[$k])
					->order("mp.number desc")
					->select();
			}else{
				$ModuleProductArr[] = $ModuleProduct->alias("mp")
					//ihziluoh 更改分表
					//	->join("wx_".$cid."_module_product_tag_list mptl ON mptl.pid =mp.id ")
					->join("wx_module_product_tag_list mptl ON mptl.pid =mp.id ")
					->join("wx_module_product_tag tag on mptl.tagId=tag.id")
					->field("mp.id,mp.name,mp.discountedPrice,mp.fixedPrice,mp.picUrl,tag.picUrl as tagPicUrl")
					->where($where)
					->order("mp.number desc")
					->select();
			}

			$i++;
		}
		if ($ModuleProductArr) {
// 			Log::write("看看2015-02-02：".$ModuleProduct->getLastSql());
			Output::instance()->objArray($ModuleProductArr);
		} else{
			Output::instance()->resultCode(code_success);
		}
	}
	/**
	 * 订单由你定价邀请好友列表
	 * 
	 */
	public function getProductPersonList($oid,$start=0,$limit=10) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		$UserWeiXinModel=M("user_weixin_info");
		Session::switchCustomer(0);	
		$PersonModel = M("module_freebuy_record");
		Session::switchCustomer($cid);
		$arr=$PersonModel->alias("a")
		->field("a.*")
		->where("a.oid=$oid")
		->limit("$start, $limit")
		->order("a.createTime desc")
		->select();

		foreach ($arr as $key => $value) {
			$fromUserName=$value["fromUserName"];
			$userInfo=$UserWeiXinModel->where("openid='$fromUserName'")->find();
			if($userInfo) {
				$arr[$key]["nickname"]=$userInfo["nickname"];
				$arr[$key]["headimgurl"]=$userInfo["headimgurl"];
			}
		}

		if ($arr) {
				$count = $PersonModel->alias('a')
					->where("a.oid=$oid")
					->count();
				Output::instance()->objArray($arr,$count);
			}else{
				Output::instance()->resultCode(code_success);
			}
	}
	/**
	 * 订单由你定价邀请好友列表
	 * 
	 */
	public function getOrderTuanList($teamId,$start=0,$limit=10) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);	
		$PersonModel = M("module_team_order");
		Session::switchCustomer($cid);
		$arr=$PersonModel->alias("a")
		->join("inner join wx_module_team_order_detail b on b.teamId=a.id")
		->join("inner join wx_module_product_order c on c.id=b.oid")
		->join("join wx_".$cid."_user_weixin_info d on c.fromUserName=d.openid")
		->field("a.id,b.createTime,d.nickname,d.headimgurl,b.role,c.fullName,c.serialNumber")
		->where("a.id=$teamId and (c.wxTransactionId<>'' or c.payType='delivery')")
		->limit("$start, $limit")
		->order("a.createTime desc")
		->select();
		if ($arr) {
				$count = $PersonModel->alias('a')
					->join("inner join wx_module_team_order_detail b on b.teamId=a.id")
					->join("inner join wx_module_product_order c on c.id=b.oid")
					->join("join wx_".$cid."_user_weixin_info d on c.fromUserName=d.openid")
					->where("a.id=$teamId and (c.wxTransactionId<>'' or c.payType='delivery')")
					->count();
				Output::instance()->objArray($arr,$count);
			}else{
				Output::instance()->resultCode(code_success);
			}
	}
	// ihziluoh  订单 添加 start

    /**
     * 查询订单信息
     *
     * @param int    $start             偏移量(其实id)
     * @param int    $limit             查询数量
     * @param null   $agent
     * @param null   $customerUserId
     * @param string $serialNumber		订单号
     * @param null   $expressNo         快递单号
     * @param string $startTime         订单起始时间
     * @param string $endTime           订单结束时间
     * @param string $phone             手机号
     * @param null   $status            订单状态
     * @param null   $deliveryType      订单物流方式
     * @param null   $orderType         订单类型
     * @param string $fullName          买家名称
     * @param string $name              商品名称
     * @param string $storeResourceName 门店名称
     * @param null   $channelId         渠道
     * @param null   $price
     * @param null   $payType
     * @param int    $batch
     * @param string $order
     * @param string $orderBy
     * @param bool    $isExport          是否为导出, 默认不传该参数为不导出, 1-导出Excel概况打印, 2-导出Excel详细
     * @param int    $vId          		供应商id
     * @param int    $syncStatus          对接状态
     * @modify lilei<LL_strive@163.com> 2017-03-29
     */
	public function getProductOrderList(
        $start              = 0,
        $limit              = 15,
        $agent              = NULL,
        $customerUserId     = NULL,
        $serialNumber       = '',
        $expressNo          = NULL,
        $startTime          = '',
        $endTime            = '',
        $phone              = '',
        $status             = NULL,
        $deliveryType       = NULL,
        $orderType          = NULL,
        $fullName           = '',
	    $name               = '',
        $storeResourceName  = '',
        $channelId          = null,
        $price              = NULL,
        $payType            = NULL,
        $batch              = 0,
        $order              = "od.createTime",
        $orderBy            = "desc",
        $isExport           = false,
		$vId				=null,
		$syncStatus			=null,
		$type 			    =null,
        $ids                =null,
        $orderChannelId 			    =null
    ) {
	    /** 1. 获得当前用户id */
		$retVal = Session::init();
		if (!$retVal) { // 如果该用户未登录, 则为非法用户, 返回
			Output::instance()->resultCode(code_access_denied);
			return;
		}

        /** 1.1 切换用户身份 */
		$cid = Session::$user["customerId"];
        $agent = Session::$user["agent"];
        $customerUserId = Session::$user["id"];
		Session::switchCustomer(0);

        /** 2. 实例化数据模型 */
		$OrderModel = M("module_product_order");
		$ProductDetailModel = M("module_product_order_detail");
		$MiVendor = M("mivendor");
        $DepotModel   = M('depot');
		$customerUser = M("customer_user");
		Session::switchCustomer($cid);

        /** 3. 组合查询数据的where条件 */
        // 是否匹配快递单号$expressNo
        isset($expressNo) && $expressNo ? $condition["od.expressNo"] = array('like','%'.$expressNo.'%') : "";
		isset($type) && $type ? $condition["od.type"] = array('eq',$type) : "";
        // 订单的delete是否等于0 - 代表未删除
        $condition['od.deleted'] = array('eq', 0);
//        $condition['isF2B'] = array('eq', 0);
		// 是否匹配订单类别
        if ($ids) $condition['od.id'] = ['in', $ids];
		if(!empty($orderType) && $orderType !== 'all' && $orderType == "orderType") {
			$condition[$orderType] = array('eq', 3);
		} else if(!empty($orderType) && $orderType !== 'all' && $orderType == 'proSource') {
			$condition['od.proSource'] = array('eq', 1);
		} else if(!empty($orderType) && $orderType !== 'all' && $orderType == 'crowdfunding') {
			$condition["od.orderType"] = array('eq', 6);
		} else if(!empty($orderType) && $orderType !== 'all' && $orderType == ORDER_TYPE_FORM) {
			$condition["od.orderType"] = array('eq', 9);
		} else if(!empty($orderType) && $orderType !== 'all') {
			$condition[$orderType] = array('eq', 1);
		} else if(!empty($orderType) && $orderType == 'all') {
			$condition["od.isTeam"] = array("eq", 0);
			$condition["od.freebuy"] = array("eq", 0);
			$condition["od.isActivity"] = array("eq", 0);
			$condition["od.orderType"] = array("EXP", 'is null');
			$condition['od.proSource'] = array('eq', 0);
		}
		// 是否匹配配送方式
		isset($deliveryType) && $deliveryType ? $condition['od.deliveryType'] = array('eq',$deliveryType) : "";
        //
        if (!empty($serialNumber)) {
			$condition['od.serialNumber'] = array('like', "%$serialNumber%");
		}
		//
		$batch ? $condition['od.batchId'] = array("EXP", "is null") : "";
		isset($syncStatus)&&$syncStatus!=null?$condition['od.syncStatus']=array('eq',$syncStatus):'';
        // 是否匹配电话号
        if (!empty($phone)) {
			$condition['od.phone'] = array('like', "%{$phone}%");
		}
		//
		isset($price) && $price ? $condition['od.price'] = array('eq', $price) : "";
        // 是否匹配开始和结束时间
		if ($startTime != '' && $endTime != '') {   // 同时匹配开始和截止时间
			$condition['od.createTime'] = array(array('egt', $startTime), array('elt', $endTime));
		} else if ($startTime != '') {  // 只匹配开始时间
			$condition["od.createTime"] = array('egt', $startTime);
		} else if ($endTime != '') {    // 只匹配结束时间
			$condition["od.createTime"] = array('elt', $endTime);
		}
		// 是否匹配买家名称
		if (!empty($fullName)) {
			$condition['_string'] = "od.fullName like '%$fullName%' or uInfo.nickname like '%$fullName%'";
		}
		// 是否匹配订单状态
		if($status != NULL) {
			$condition['od.status'] = array('eq', $status);
		} else {
			$condition['od.status'] = array(array('neq', ''), array('neq', order_status_notsubmit), 'and'); // not submit order
		}
		// 是否匹配支付方式
		if($payType != NULL) {
			$condition['od.payType'] = array('eq',$payType);
		}
//		 if($deliveryType != NULL){
//		 	$condition['deliveryType'] = array('eq',$deliveryType);
//		 }
        // 是否匹配商品名称http://newtest.mboxone.com/test/call.html?userName=&customerId=50&module=personCenter&method=logout
		$name ? $condition['detail.name'] = array("like","%$name%") : "";
        // 是否匹配门店名称
        if (!empty($storeResourceName)) {
            $condition['_string'] = "od.storeResourceName like '%$storeResourceName%'";
        }
        // 进行用户身份不一样的相关数据过滤
		if (!empty($agent) && Session::isVendor()) {
            if(!($vId || $orderChannelId)){
                $channelId ? $condition['od.fromCustomerId'] = array('eq',$channelId) : "";
                $vwhere["id"] = $customerUserId;
                $varr = $customerUser->field("vid")->where($vwhere)->find();
                $Vendors = R('Vendor/getMivendorChildList',array($varr["vid"],'string'));
                $map['od.vId'] = array('in',$Vendors);
                $map['od.channelId']  = array('in',$Vendors);
                $map['_logic'] = 'or';
                $condition['_complex'] = $map;

            }
		} else if (!empty($agent) && $agent =='depot') {    // 登录身份是仓库管理员
            // 判断用户身份, 如果是仓库管理员身份, 新增一个仓库管理员筛选条件(查询出该管理员所辖仓库的订单id)
            // 从仓库表中查出该管理员管理的仓库id
            $where          = array();
            $where['cuid']  = array('eq', Session::$user['id']);
            $depot_id       = $DepotModel->where($where)->field('id')->select();

            $condition = Array(); // 本地测试用, 别的条件会过滤掉订单
            // 增加仓库管理员对订单的筛选条件
            $condition['od.depotid'] = array('eq', $depot_id[0]['id']);
        } else {
			$condition['od.fromCustomerId'] = array('eq',$cid);
		}
        if(!empty($vId) && !empty($orderChannelId)){
            $Vendors = R('Vendor/getMivendorChildList',array($vId,'string'));
            $orderChannelIds = R('Vendor/getMivendorChildList',array($orderChannelId,'string'));
            $condition['od.vId'] = array('in',$Vendors);
            $condition['od.channelId']  = array('in',$orderChannelIds);
        }elseif (!empty($vId) && empty($orderChannelId)){
            $Vendors = R('Vendor/getMivendorChildList',array($vId,'string'));
            $condition['od.vId'] = array('IN',$Vendors);
        }elseif (empty($vId) && !empty($orderChannelId)){
            $orderChannelIds = R('Vendor/getMivendorChildList',array($orderChannelId,'string'));
            $condition['od.ChannelId'] = array('IN',$orderChannelIds);
        }
		/** 4. 判断请求想要的数据类型 */
		if (!$isExport) {   // 不需要导出数据
			if($orderType == ORDER_TYPE_FORM){
				$arr = $OrderModel->alias('od')
					->join('inner join wx_module_product_order_detail b on od.id=b.oid')
					->join('wx_'.$cid.'_user_weixin_info c on od.uId=c.userId')
					->join('wx_'.$cid.'_user d on od.uId=d.id')
					->join('wx_form e on b.pid=e.id')
					->where($condition)
					->order('createTime desc')
					->limit($start, $limit)
					->field('od.id, od.serialNumber, od.createTime, od.status, od.price, od.fullName, od.phone, c.nickname,
			c.headimgurl, d.fullName as spareName, d.phone as sparePhone, b.name as formName,e.type as isPay,
			 b.pid as formId')
					->select();
			}else{
				$orderList = $OrderModel
					->alias("od")
					->join("wx_module_product_order_detail detail on od.id = detail.oid")
					->join("wx_customer_user cuser on od.fromCustomerId = cuser.customerId and cuser.agent = 'business'")
					->join("wx_" . $cid . "_user_weixin_info uInfo on uInfo.openid = od.fromUserName")
					->field("od.id")
					->where($condition)
					->group("od.id")
					->limit($start, $limit)
					->order("$order $orderBy")
					->select();
				foreach ($orderList as $key => $value) {
					$oids[] = $value["id"];
				}
				$oids = implode(",", $oids);
				$arr = $OrderModel
					->alias("od")
					->field("od.phone,od.points,od.id, od.isChainOrder, od.serialNumber, od.expressNo, od.fullName, detail.name,detail.picUrl,
				         c.firstSpecificName, c.secSpecificName, od.isTeam, od.freebuy, od.teamId, od.payTime,
				         detail.count, detail.isVendorCut, od.status, detail.serialNumber as proSeralNumber, 
				         od.createTime, cuser.fullName as userName, detail.price, detail.customizedName1,
				         detail.customizedDescription1, detail.customizedName2, detail.customizedDescription2, 
				         detail.customizedName3, detail.customizedDescription3,info.nickname,info.headimgurl")//,ven.name as vname,ven.logo as vlog 供应商字段
					->join("wx_miyouquan as quan on quan.id = od.qId")
					->join("wx_module_team_order tm on tm.id = od.teamId")
					->join("wx_module_product_order_detail detail on od.id = detail.oid")
					->join("wx_module_product_order_detail_specification c on detail.id = c.did")
					->join("wx_customer_user cuser on od.fromCustomerId = cuser.customerId and cuser.agent = 'business'")
					->join("wx_" . $cid . "_user_weixin_info info on info.userId=od.uId")
					//->join("wx_mivendor as ven on ven.id=od.vId")
					->where("od.id in ($oids)")
					->order("$order $orderBy")
					->select();
			}
			if ($arr) {
				if($orderType == ORDER_TYPE_FORM){
					foreach($arr as $k=>$v){
						if($v['isPay'] == 1){
							if($v['status'] == ORDER_STATUS_PAYING){
								$v['changeStatus'] = [
									['name'=>'已关闭','val'=>'closed']
								];
							}else if($v['status'] == order_status_refund || $v['status'] == ORDER_STATUS_REFUNDEDPART) {
								$v['changeStatus'] = [
									['name'=>'已关闭','val'=>'closed'],
									['name'=>'已取消','val'=>'cancel']
								];
							}else if($v['status'] == order_status_delivering){
								$v['changeStatus'] = [
									['name'=>'已确认','val'=>'ok'],
									['name'=>'已取消','val'=>'cancel']
								];
							}else if($v['status'] == order_status_ok){
								$v['changeStatus'] = [
									['name'=>'已取消','val'=>'cancel']
								];
							}else if($v['status'] == order_status_cancel){
								$v['changeStatus'] = [
									['name'=>'已确认','val'=>'ok'],
									['name'=>'已关闭','val'=>'closed']
								];
							}else{
								$v['changeStatus'] = [];
							}
						}else{
							if($v['status'] == order_status_submission){
								$v['changeStatus'] = [
									['name'=>'已确认','val'=>'ok'],
									['name'=>'已关闭','val'=>'closed'],
									['name'=>'已取消','val'=>'cancel']
								];
							}else if($v['status'] == order_status_ok){
								$v['changeStatus'] = [
									['name'=>'已取消','val'=>'cancel']
								];
							}else if($v['status'] == order_status_cancel){
								$v['changeStatus'] = [
									['name'=>'已确认','val'=>'ok'],
									['name'=>'已关闭','val'=>'closed']
								];
							}else{
								$v['changeStatus'] = [];
							}
						}
						$arr[$k] = $v;
					}
				}else {
					$arr = self::changeOrderSerialNumber($arr);
					foreach ($arr as $key => $value) {
						$rowspan = 1;
						for ($i = $key + 1; $i < count($arr); $i++) {
							$v = $arr[$i];

							if ($value['id'] == $v['id']) {
								$rowspan++;
							} else {
								break;
							}
						}
						if ($value['isChainOrder'] == 1) {
							$arr[$key]["color"] = "#ff0000";
						}
						$arr[$key]['rowspan'] = $rowspan;
						$oid = $value["id"];
						$str = "select round(sum(price*count),2) as amount,round(sum(freePrice*count),2) as freeAmount from wx_module_product_order_detail where oid=$oid";
						$orderDetail = $ProductDetailModel->query($str);
						if (count($orderDetail) > 0) {
							$arr[$key]["amount"] = $orderDetail[0]["amount"];
							$arr[$key]["freeAmount"] = $orderDetail[0]["freeAmount"];
						}
					}
				}
				if($orderType == ORDER_TYPE_FORM){
					$count = $OrderModel->alias('od')
						->join('inner join wx_module_product_order_detail b on od.id=b.oid')
						->where($condition)
						->field('od.id')
						->count();
				}else{
					$count = $OrderModel->alias("od")
						->join("wx_module_product_order_detail detail on od.id=detail.oid")
						->join("wx_customer_user cuser on od.fromCustomerId=cuser.customerId and cuser.agent='business'")
						->join("wx_".$cid."_user_weixin_info uInfo on uInfo.openid=od.fromUserName")
						->where($condition)
						->group("od.id")
						->field("od.id")
						->select();
					$count = count($count);
				}
				Output::instance()->objArray($arr,$count);
			} else {
				$return['code'] = 0;
				$return['msg'] = 'ok';
				$return['results'] = [];
				$return['total'] = 0;
				Output::instance()->object($return);
			}
		} else if($isExport == 1) { // 导出Excel概况打印
            /** 导出数据量比较大, 这里设置超时时间无限制, 无论之前脚本运行多长时间, 此函数都会重启超时计时器, 从0重新计时 */
            set_time_limit(0) ;
			$arr = $OrderModel
                ->alias("od")
			    ->join("wx_module_product_order_detail detail ON detail.oid = od.id")
//                ->join("wx_miyouquan as quan on quan.id=od.qId")
//                ->join("wx_quan_user as quser on od.miUid=quser.uid")
//                ->join("wx_all_user auser on quser.uid = auser.id")
                ->join("wx_module_product_order_detail_specification pSpec ON detail.id = pSpec.did")
                ->join("wx_customer_user cuser on od.fromCustomerId = cuser.customerId and cuser.agent = 'business'")
                ->join("wx_" . $cid . "_user_weixin_info uInfo on uInfo.openid = od.fromUserName")
                ->join("wx_depot depot on od.depotid = depot.id")
                ->where($condition)
                ->order("fullName desc,$order $orderBy")
                ->field("od.serialNumber,od.province,od.city,od.country, od.expressNo, detail.name, detail.count, od.remark, od.fullName,
                         od.address, od.phone, od.sellerRemark, pSpec.firstSpecificName, pSpec.secSpecificName,
                         od.updateTime, od.IDName, od.IDNumber, depot.name as depotName,uInfo.nickname")
                ->group("detail.id")
                ->select();

			$data[0] = array(
						'temp'              => "",
						'serialNumber'      => '订单号',
						'name'              => '商品名称',
						'firstSpecificName' => '规格1',
						'secSpecificName'   => '规格2',
						'count'             => '数量',
                        'depotName'         => '仓库名称',
						'fullName'          => '买家姓名',
//						'nickname' 			=>'买家昵称',
						'phone'             => '买家手机电话',
						'express'           => '物流公司',
						'expressNo'         => '物流单号',
						'remark'            => '买家备注',
						'province'          => '省',
						'city'              => '市',
						'area'              => '县',
						'street'            => '地址',
						'address'           => '买家收货地址',
						'sellerRemark'      => '卖家备注',
						'updateTime'        => '下单时间',
						'IDName'            => "真实姓名",
						'IDNumber'          => '身份证号码',
						'isNum'             => '5',
						'istitle'           => '1'
				);
			foreach ($arr as $k1 => $v1) {
				if ($v1["code"]) {
					 $v1["code"]    = '';
					 $v1["company"] = '';
				}
				$data[$k1+1]['temp']                = '';
				$data[$k1+1]['serialNumber']        = $v1['serialNumber'];
				$data[$k1+1]['name']                = $v1['name'];
				$data[$k1+1]['firstSpecificName']   = $v1['firstSpecificName'];
				$data[$k1+1]['secSpecificName']     = $v1['secSpecificName'];
				$data[$k1+1]['count']               = $v1['count'];
                $data[$k1+1]['depotName']           = $v1['depotName'];
				$data[$k1+1]['fullName']            = $v1['fullName'];
//				$data[$k1+1]['nickname']            = $v1['nickname'];
				$data[$k1+1]['phone']               = $v1['phone'];
				$data[$k1+1]['express']             = '';
				$data[$k1+1]['expressNo']           = $v1['expressNo'];
				$data[$k1+1]['remark']              = $v1['remark'];
				if(!$v1['province']){
					$address = self::addressFomate($v1['address']);
					$data[$k1+1]['province']            = $address['province'];
					$data[$k1+1]['city']                = $address['city'];
					$data[$k1+1]['area']                = $address['area'];
					$data[$k1+1]['street']              = $address['street'];
					$data[$k1+1]['address']             = $v1['address'];
				}else{
					$data[$k1+1]['province']            = $v1['province'];
					$data[$k1+1]['city']                = $v1['city'];
					$data[$k1+1]['area']                = $v1['country'];
					$data[$k1+1]['street']              = $v1['address'];
					$data[$k1+1]['address']             = $v1['province'].$v1['city'].$v1['country'].$v1['address'];
				}
				$data[$k1+1]['sellerRemark']        = $v1['sellerRemark'];
				$data[$k1+1]['updateTime']          = $v1['updateTime'];
				$data[$k1+1]['IDName']              = $v1['IDName'];
				$data[$k1+1]['IDNumber']            = $v1['IDNumber'];
			}
			Output::instance()->objArrayExcel('订单信息'.date("Y-m-d H:i:s"), '', $data);
		} else if($isExport == 2) { // 导出Excel详细
            /** 导出数据量比较大, 这里设置超时时间无限制 */
            set_time_limit(0) ;
			$userId = session("id");
			$userInfo = $customerUser->where("id=$userId")->field("supplyRelation")->find();

            $arr = $OrderModel
                ->alias("od")
                ->join("wx_module_product_order_detail detail on detail.oid = od.id")
                ->join("wx_micontent content on content.id = detail.contentId")
                ->join("wx_module_product pro on detail.pid = pro.id")
                ->join("wx_miyouquan as quan on quan.id = od.qId")
                ->join("wx_" . $cid . "_user_weixin_info as userWx on od.miUid = userWx.userId")
                ->join("wx_" . $cid . "_user auser on od.miUid = auser.id")
                ->join("wx_module_product_order_detail_specification pSpec ON detail.id = pSpec.did")
                ->join("wx_store store on od.storeResourceId = store.id")
                ->join("wx_customer_user cuser on od.fromCustomerId = cuser.customerId and cuser.agent = 'business'")
                ->join("wx_" . $cid . "_user_weixin_info uInfo on uInfo.openid = od.fromUserName")
                ->join("wx_" . $cid . "_user sInfo on sInfo.id = od.saleSource")
                ->where($condition)
                ->order("$order $orderBy")
                ->field("od.isChainOrder, od.serialNumber, od.fullName, od.phone, detail.name, pSpec.firstSpecificName,
                         pSpec.secSpecificName, detail.count, od.price, detail.isVendorCut, detail.isChannelCut,
                         detail.saleCut, od.payType, od.status, store.name as storeName, store.phone as storePhone,
                         store.address as storeAddress, detail.price as proPrice, od.address,od.province,od.city,od.country, quan.name as qname,
                         userWx.nickname as preNickName, auser.fullName as aname, auser.phone as aphone, od.expressNo, od.remark,
                         od.createTime, od.IDName, od.IDNumber, detail.customizedName1, detail.customizedDescription1,
                         detail.customizedName2, detail.customizedDescription2, detail.customizedName3,
                         detail.customizedDescription3, detail.customizedInfo,detail.serialNumber as proSerialNumber,detail.foreignName,detail.supplierSkuNo,detail.country,detail.category,detail.specificUnit,
                        detail.specificName,pSpec.firstSpecificUnit,pSpec.secSpecificUnit,uInfo.nickname,od.type,sInfo.fullName as saleSourceName,sInfo.phone as saleSourcePhone,content.title as contentTitle")
                ->group("detail.id")
                ->select();
			$data = null;
			$data[0] = array(
						'serialNumber'      => '订单编号',
						'fullName'          => '姓名',
//						'nickname'          => '昵称',
						'phone'             => '手机号码',
						'name'              => '商品名称',
						'foreignName'       => '商品外文名称',
						'country'       	=> '国家',
                        'proSerialNumber'   => '商品条码',
						'supplierSkuNo'   	=> '商品编码',
						'category'   		=> '展示分类',
						'firstSpecificName' => '规格1',
						'firstSpecificUnit' => '规格1单位',
						'secSpecificName'   => '规格2',
						'secSpecificUnit' 	=> '规格2单位',
						'count'             => '数量',
						'price'             => '金额',
						'isVendorCut'       => '供货价',
						'saleCut'           => '销售分成',
						'payType'           => '支付方式',
						'status'            => '订单状态',
						'storeName'         => '门店名称',
						'storePhone'        => '门店电话',
						'storeAddress'      => '门店地址',
						'address'           => '地址',
						'qname'             => '密友圈',
						'nickName'          => '密友昵称',
						'aname'             => '密友姓名',
						'aphone'            => '密友电话',
						'expressNo'         => '快递单号',
						'remark'            => '买家备注',
						'createTime'        => '下单时间',
						'IDName'            => '真实姓名',
						'IDNumber'          => '身份证号码',
						'customizedInfo'    => '定制信息',
						'saleSourceName'    => '销售源姓名',
						'saleSourcePhone'   => '销售源电话',
						'contentTitle'      => '来源文章标题',
						'istitle'           => '1',         // 标识Key
						'isNum'             => '7,8'        // 标识是数值的列
				);
			foreach ($arr as $k1 => $v1) {
			    $v2 = null;
                $v2['serialNumber'] = $v1['serialNumber'];
                $v2['fullName']     = $v1['fullName'];
//                $v2['nickname']     = $v1['nickname'];
                $v2['phone']        = $v1['phone'];
                $v2['name']         = $v1['name'];
				$v2['foreignName']  = $v1['foreignName'];
				$v2['country']  = $v1['country'];
				$v2['proSerialNumber'] = $v1['proSerialNumber'];
				$v2['supplierSkuNo']  = $v1['supplierSkuNo'];
				$v2['category']  = $v1['category'];
				if( $v1['firstSpecificName']){
					$v2['firstSpecificName'] = $v1['firstSpecificName'];
					$v2['firstSpecificUnit'] = $v1['firstSpecificUnit'];
					$v2['secSpecificName']   = $v1['secSpecificName'];
					$v2['secSpecificUnit'] = $v1['secSpecificUnit'];
				}else{
					$v2['firstSpecificName'] = $v1['specificName'];
					$v2['firstSpecificUnit'] = $v1['specificUnit'];
					$v2['secSpecificName']   = '';
					$v2['secSpecificUnit'] = '';
				}
                $v2['count']             = $v1['count'];
                $v2['price']             = $v1['proPrice'];
                if($v1['isChainOrder'] && $userInfo['supplyRelation'] == 2) {
                    $v2['isVendorCut'] = $v1['isChannelCut'];
                } else {
                    $v2['isVendorCut'] = $v1['isVendorCut'];
                }
                $v2['saleCut']           = $v1['saleCut'];
                $payType = [
                    'wxpay'     => '微信支付',
                    'tenpay'    => '银行卡支付',
                    'delivery'  => '货到付款',
                    'alipay'    => '支付宝'
                ];
                $v2["payType"] = $payType[$v1["payType"]];
                $status = [
                    'ok'                => '交易成功',
                    'closed'            => '交易关闭',
                    'paying'            => '等待付款',
                    'delivering'        => '等待发货',
                    'deliveringtostore' => '等待配送到门店',
                    'delivered'         => '已经发货',
                    'deliveredtostore'  => '已配送到门店',
                    'refund'            => '已退款',
                    'refundedpart'      => '已部分退款',
                    'refunding'         => '退款中',
                    'payingconfirm'     => '付款确认中',
                    'partake'           => '夺宝中',
                    'teaming'           => '组团中',
                    'paypart'           => '代言中',
                    'ordersign'         => '已报名',
                    'confirmsign'       => '已确认报名',
                    'canclesign'        => '已取消报名',
                    'supported'         => '众筹中',
                ];
				if($v1['type'] == ORDER_TYPE_FORM){
					$status = [
						'ok'                => '已确认',
						'closed'            => '已关闭',
						'paying'            => '待付款',
						'delivering'        => '已取消',
						'cancel'        => '已付款',
						'submission'        => '已提交',
						'refund'            => '已退款',
						'refundedpart'      => '已部分退款',
					];
				}
                $v2["status"] = $status[$v1["status"]];
                $v2['storeName']    = $v1['storeName'];
                $v2['storePhone']   = $v1['storePhone'];
                $v2['storeAddress'] = $v1['storeAddress'];
                $v2['address']      = $v1['province'].$v1['city'].$v1['country'].$v1['address'];
                $v2['qname']        = $v1['qname'];
                $v2['nickName']     = self::filterEmoji($v1['preNickName']);
                $v2['aname']        = $v1['aname'];
                $v2['aphone']       = $v1['aphone'];
                $v2['expressNo']    = $v1['expressNo'];
                $v2['remark']       = $v1['remark'];
                $v2['createTime']   = $v1['createTime'];
                $v2['IDName']       = $v1['IDName'];
                $v2['IDNumber']     = $v1['IDNumber'];
				$customizedInfo = json_decode($v1['customizedInfo'],true);
				$temp = '';
				if(count($customizedInfo)>0){
					foreach($customizedInfo as $key=>$customized){
						$temp.=$customized['name'].':'.$customized['description']."|";
					}
				}else{
					if($v1['customizedName1']){
						$temp.= $v1['customizedName1'] . ":" . $v1['customizedDescription1'];
					}
					if($v1['customizedName2']){
						$temp.= $v1['customizedName2'] . ":" . $v1['customizedDescription2']."|";
					}
					if($v1['customizedName3']){
						$temp.= $v1['customizedName3'] . ":" . $v1['customizedDescription3']."|";
					}
				}
				$v2['customizedInfo']     = $temp;
				$v2['saleSourceName']     = $v1['saleSourceName'];
                $v2['saleSourcePhone']     = $v1['saleSourcePhone'];
                $v2['contentTitle']     = $v1['contentTitle'];
				$data[] = $v2;
			}

//            Output::instance()->objArrayCsv($data,null,'订单信息详情'.date("Y-m-d H:i:s").'.csv');
			Output::instance()->objArrayExcel('订单信息详情'.date("Y-m-d H:i:s"), '', $data);
		}else if($isExport == 3){
			set_time_limit(0) ;
			$userId = session("id");
			$userInfo = $customerUser->where("id=$userId")->field("supplyRelation")->find();

			$arr = $OrderModel
				->alias("od")
				->join("wx_miyouquan as quan on quan.id = od.qId")
				->join("wx_" . $cid . "_user_weixin_info as quser on od.miUid = quser.userId")
				->join("wx_" . $cid . "_user auser on quser.userId = auser.id")
				->join("wx_store store on od.storeResourceId = store.id")
				->join("wx_customer_user cuser on od.fromCustomerId = cuser.customerId and cuser.agent = 'business'")
				->join("wx_" . $cid . "_user_weixin_info uInfo on uInfo.openid = od.fromUserName")
				->where($condition)
				->order("$order $orderBy")
				->field("od.isChainOrder, od.serialNumber, od.fullName, od.phone, od.price,
                         od.payType, od.status, store.name as storeName, store.phone as storePhone,
                         store.address as storeAddress,od.province,od.city,od.country,  od.address, quan.name as qname,
                         quser.nickname as preNickName, auser.fullName as aname, auser.phone as aphone, od.expressNo, od.remark,
                         od.createTime, od.IDName, od.IDNumber,od.price,od.logisticsCost,od.couponMoney,od.type")
				->group("od.id")
				->select();
			$data = null;
			$data[0] = array(
				'serialNumber'      => '订单编号',
				'fullName'          => '姓名',
				'phone'             => '手机号码',
				'price'             => '订单金额',
				'logisticsCost'     => '运费',
				'couponMoney'       => '优惠金额',
				'payType'           => '支付方式',
				'status'            => '订单状态',
				'storeName'         => '门店名称',
				'storePhone'        => '门店电话',
				'storeAddress'      => '门店地址',
				'address'           => '地址',
				'qname'             => '密友圈',
				'nickName'          => '密友昵称',
				'aname'             => '密友姓名',
				'aphone'            => '密友电话',
				'expressNo'         => '快递单号',
				'remark'            => '买家备注',
				'createTime'        => '下单时间',
				'IDName'            => '真实姓名',
				'IDNumber'          => '身份证号码',
				'istitle'           => '1',         // 标识Key
				'isNum'             => '3'        // 标识是数值的列
			);
			foreach ($arr as $k1 => $v1) {
				$v2 = null;
				$v2['serialNumber'] = $v1['serialNumber'];
				$v2['fullName']     = $v1['fullName'];
				$v2['phone']        = $v1['phone'];
				$v2['price']        = $v1['price'];
				$v2['logisticsCost']= $v1['logisticsCost'];
				$v2['couponMoney']  = $v1['couponMoney'];
				$payType = [
					'wxpay'     => '微信支付',
					'tenpay'    => '银行卡支付',
					'delivery'  => '货到付款',
					'alipay'    => '支付宝'
				];
				$v2["payType"] = $payType[$v1["payType"]];
				$status = [
					'ok'                => '交易成功',
					'closed'            => '交易关闭',
					'paying'            => '等待付款',
					'delivering'        => '等待发货',
					'deliveringtostore' => '等待配送到门店',
					'delivered'         => '已经发货',
					'deliveredtostore'  => '已配送到门店',
					'refund'            => '已退款',
					'refundedpart'      => '已部分退款',
					'refunding'         => '退款中',
					'payingconfirm'     => '付款确认中',
					'partake'           => '夺宝中',
					'teaming'           => '组团中',
					'paypart'           => '代言中',
					'ordersign'         => '已报名',
					'confirmsign'       => '已确认报名',
					'canclesign'        => '已取消报名',
					'supported'         => '众筹中',
				];
				if($v1['type'] == ORDER_TYPE_FORM){
					$status = [
						'ok'                => '已确认',
						'closed'            => '已关闭',
						'paying'            => '待付款',
						'delivering'        => '已取消',
						'cancel'        => '已付款',
						'submission'        => '已提交',
						'refund'            => '已退款',
						'refundedpart'      => '已部分退款',
					];
				}
				$v2["status"] = $status[$v1["status"]];
				$v2['storeName']    = $v1['storeName'];
				$v2['storePhone']   = $v1['storePhone'];
				$v2['storeAddress'] = $v1['storeAddress'];
				$v2['address']      = $v1['province'].$v1['city'].$v1['country'].$v1['address'];
				$v2['qname']        = $v1['qname'];
				$v2['nickName']     = self::filterEmoji($v1['preNickName']);
				$v2['aname']        = $v1['aname'];
				$v2['aphone']       = $v1['aphone'];
				$v2['expressNo']    = $v1['expressNo'];
				$v2['remark']       = $v1['remark'];
				$v2['createTime']   = $v1['createTime'];
				$v2['IDName']       = $v1['IDName'];
				$v2['IDNumber']     = $v1['IDNumber'];
				$data[] = $v2;
			}
			Output::instance()->objArrayExcel('订单结算详情'.date("Y-m-d H:i:s"), '', $data);
		}
	}

	public function importProduct($fileName){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$productModel= M("module_product");
		$productSpec = M("module_product_specification");
		Session::switchCustomer($cid);
		$filePath = UPLOAD_BASE_PATH . $fileName;
		try{
			$objPHPExcel = PHPExcel_IOFactory::load($filePath);
		} catch (PHPExcel_Exception $e) {
			Output::instance()->resultCode(code_excel_load_fail, $e->getMessage());
			return;
		}
		$count = $objPHPExcel->getSheetCount();
		for($sheetIndex = 0;$sheetIndex<$count;$sheetIndex++) {
			$sheet = $objPHPExcel->getSheet($sheetIndex); // 读取第一個工作表
			$highestRow = $sheet->getHighestRow(); // 取得总行数
			$highestColumm = $sheet->getHighestColumn(); // 取得总列数
			$highestColumm = PHPExcel_Cell::columnIndexFromString($highestColumm);
			for ($row = 1; $row <= $highestRow; $row++) {//行数是以第1行开始
				$data = null;$where=null;
				for ($column = 0; $column < $highestColumm; $column++) {//列数是以第0列开始
					$value = $sheet->getCellByColumnAndRow($column, $row)->getValue();
					if($row==1){
						switch(trim($value)){
							case '规格1':
								$firstSpecificColumn = $column;
								break;
							case '规格2':
								$secSpecificColumn = $column;
								break;
							case '库存':
								$inventoryCountColumn = $column;
								break;
							case '商品条码':
								$serilNumberColumn = $column;
								break;
							case '原价':
								$fixedPriceColumn = $column;
								break;
							case '折扣价':
								$discountedPriceColumn = $column;
								break;
							case '供货价':
								$supplyPriceColumn = $column;
								break;
							case '渠道价':
								$channelSupplyPriceColumn = $column;
								break;
							case '平台分成':
								$platCutColumn = $column;
								break;
							case '销售分成':
								$saleCutColumn = $column;
								break;
							case '密友价':
								$miPriceColumn = $column;
								break;
							case '税率':
								$tariffColumn = $column;
								break;
							case '报关价格':
								$customsPriceColumn = $column;
								break;
						}
					}
					if($row>1){
						if($column===$serilNumberColumn){
							$serialNumber = trim($value);
						}else if($column===$firstSpecificColumn){
							$firstSpecific = trim($value);
						}else if($column===$secSpecificColumn){
							$secSpecific = trim($value);
						}else if($column===$inventoryCountColumn){
							$inventoryCount = trim($value);
						}else if($column===$fixedPriceColumn){
							$fixedPrice = trim($value);
						}else if($column===$discountedPriceColumn){
							$discountedPrice = trim($value);
						}else if($column===$supplyPriceColumn){
							$supplyPrice = trim($value);
						}else if($column===$platCutColumn){
							$platCut = trim($value);
						}else if($column===$saleCutColumn){
							$saleCut = trim($value);
						}else if($column===$miPriceColumn){
							$miPrice = trim($value);
						}else if($column===$tariffColumn){
							$tariff = trim($value);
						}else if($column===$customsPriceColumn){
							$customsPrice = trim($value);
						}else if($column==$channelSupplyPriceColumn){
							$channelSupplyPrice = trim($value);
						}
						if(!$serialNumber){
							continue;
						}

					}
				}
				$inventoryCount?$data['inventoryCount']=$inventoryCount:"";
				$fixedPrice?$data['fixedPrice']=$fixedPrice:"";
				$discountedPrice?$data['discountedPrice']=$discountedPrice:"";
				$supplyPrice?$data['supplyPrice']=$supplyPrice:"";
				$platCut?$data['platCut']=$platCut:"";
				$saleCut?$data['saleCut']=$saleCut:"";
				$miPrice?$data['miPrice']=$miPrice:"";
				$tariff?$data['tariff']=$tariff:"";
				$customsPrice?$data['customsPrice']=$customsPrice:"";
				$channelSupplyPrice?$data['channelSupplyPrice']=$channelSupplyPrice:"";
				if($firstSpecific){
					$where['b.serialNumber']=array("eq",$serialNumber);
					$where['a.fromCustomerId']=array("eq",$cid);
					$where['a.supportSpecification']=array("eq",1);
					$result = $productSpec->alias("b")
						->join("inner join wx_module_product a on b.pid=a.id")
						->field("b.id")
						->where($where)
						->find();
					if($result){
						$productSpec->where("id=".$result['id'])->save($data);
					}
				}else{
					$where['serialNumber']=array("eq",$serialNumber);
					$where['fromCustomerId']=array("eq",$cid);
					$productModel->where($where)->save($data);
				}
			}
		}
		Output::instance()->resultCode();
	}

    /**
     * 订单管理模块导入功能
     * - 菠萝派接口实现之前, 使用订单导入来实现订单发货状态的改变
     * @modify lilei<LL_strive@163.com> 2017-04-21
     */
    public function batchUpdateOrder()
    {
        /** 1. 后台操作, 先判断用户登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /** 2. 实例化相关数据模型 */
        Session::switchCustomer(0);
        $order = M("module_product_order");

        /** 3. 拿到文件在服务器上的临时位置 */
        $filePath = $_FILES['file']['tmp_name'];

        /** 4. 加载PHPExcel组件 */
        vendor("PHPExcel.PHPExcel");
        $PHPReader = new PHPExcel_Reader_Excel2007();

        // 4.1 判断文件格式
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                echo '不是excel表格!';
                return;
            }
        }

        // 4.2 载入excel文件
        $PHPExcel = $PHPReader->load($filePath);

        /** 5. 处理数据 */
        $count = $PHPExcel->getSheetCount();    // 获得该Excel文件中工作表个数
        for ($sheetIndex = 0; $sheetIndex < $count; $sheetIndex++) {
            $sheet          = $PHPExcel->getSheet($sheetIndex); // 读取第一個工作表
            $highestRow     = $sheet->getHighestRow();          // 取得总行数
            $highestColumm  = $sheet->getHighestColumn();       // 取得总列数

            $highestColumm = PHPExcel_Cell::columnIndexFromString($highestColumm);
            for ($row = 1; $row <= $highestRow; $row++) {   // 行数是以第1行开始(Excel表格导致, 并不是为了去掉字段名)
                for ($column = 0; $column < $highestColumm; $column++) {    // 列数是以第0列开始

                    // 5.1 转Exc表格数据
                    $value = $sheet->getCellByColumnAndRow($column, $row)->getValue();
                    if ($row == 1) {    // 处理字段名
                        switch (trim($value)) {
                            case '订单号':
                                $serialNumberColumn = $column;
                                break;
                            case '物流公司':
                                $expressColumn = $column;
                                break;
                            case '物流单号':
                                $expressNoColumn = $column;
                                break;
                            case '卖家备注':
                                $sellerRemarkColumn = $column;
                                break;
                        }
                    }
                    if ($row > 1) {     // 处理字段值
                        switch ($column) {
                            case $serialNumberColumn:
                                $serialNumber = trim($value);
                                break;
                            case $expressColumn:
                                $expressName = trim($value);
                                break;
                            case $expressNoColumn:
                                $expressNo = trim($value);
                                break;
                            case $sellerRemarkColumn:
                                $sellerRemark = trim($value);
                                break;
                        }
                        $status = 'delivered';
                    }
                }

                // 5.2 修改订单状态
                if ($row > 1 && $serialNumber && $expressNo) {
                    $where['serialNumber'] = array('eq', $serialNumber);
                    $orderInfo = $order->where($where)->find();

                    if ($orderInfo['status'] == order_status_delivering || $orderInfo['status'] == 'supported') {
                        Session::switchCustomer($orderInfo['fromCustomerId']);

                        // 修改订单
                        $this->updateOrderByOrderId($orderInfo['id'], null, $sellerRemark, $status, $expressName, $expressNo);
                    }
                }
            }
        }
    }
	public function addressFomate($addr){
		$tempLength=0;
		if(stripos($addr,'省')){
			$provinceIndex = stripos($addr,'省')+strlen('省');
		}else if(stripos($addr,'市')){
			$provinceIndex = stripos($addr,'市')+strlen('市');
		}else if(stripos($addr,'自治区')){
			$provinceIndex = stripos($addr,'自治区')+strlen('自治区');
		}else if(stripos($addr,'特别行政区')){
			$provinceIndex = stripos($addr,'特别行政区')+strlen('特别行政区');
		}else{
			$provinceIndex=0;
		}
		$tempLength = $provinceIndex;
		$province = substr($addr,0,$tempLength);
		if(stripos($addr,'市',$provinceIndex)){
			$cityIndex = stripos($addr,'市',$provinceIndex)+strlen('市');
		}else if(stripos($addr,'自治州',$provinceIndex)){
			$cityIndex = stripos($addr,'自治州',$provinceIndex)+strlen('自治州');
		}else if(stripos($addr,'周边',$provinceIndex)){
			$cityIndex = stripos($addr,'周边',$provinceIndex)+strlen('周边');
		}else if(stripos($addr,'盟',$provinceIndex)){
			$cityIndex = stripos($addr,'盟',$provinceIndex)+strlen('盟');
		}else if(stripos($addr,'地区',$provinceIndex)){
			$cityIndex = stripos($addr,'地区',$provinceIndex)+strlen('地区');
		}else if(stripos($addr,'行政区划',$provinceIndex)){
			$cityIndex = stripos($addr,'行政区划',$provinceIndex)+strlen('行政区划');
		}else{
			$cityIndex =0;
		}
		$tempLength=$cityIndex-$provinceIndex;
		if($tempLength>0){
			$city = substr($addr,$provinceIndex,$tempLength);
		}
		if(stripos($addr,'县',$cityIndex)){
			$areaIndex = stripos($addr,'县',$cityIndex)+strlen('县');
		}else if(stripos($addr,'区',$cityIndex)){
			$areaIndex = stripos($addr,'区',$cityIndex)+strlen('区');
		}else if(stripos($addr,'市',$cityIndex)){
			$areaIndex = stripos($addr,'市',$cityIndex)+strlen('市');
		}else if(stripos($addr,'旗',$cityIndex)){
			$areaIndex = stripos($addr,'旗',$cityIndex)+strlen('旗');
		}else if(stripos($addr,'海域',$cityIndex)){
			$areaIndex = stripos($addr,'海域',$cityIndex)+strlen('海域');
		}else{
			$areaIndex = 0;
		}
		$tempLength=$areaIndex-$cityIndex;
		if($tempLength>0){
			$area = substr($addr,$cityIndex,$tempLength);
			$tempLength = $cityIndex+strlen($area);
			$street = substr($addr,$tempLength);
		}else{
			$street = substr($addr,$cityIndex);
		}
		// 对省做特殊处理 e.g.收货地址:山东省
        $arr_province = explode(':', $province);
		$result['province']=$arr_province[count($arr_province) - 1];
		$result['city']=$city;
		$result['area']=$area;
		$result['street'] = $street;
		return $result;
	}
	public function changeOrderSerialNumber($arr){	
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);	
		$orderModule = m('module_product_order');
		Session::switchCustomer($cid);		
		foreach($arr as $key => $value){
//			$where['serialNumber'] = $value['serialNumber'];
//			$check = $orderModule -> where($where)->count();
//
//			if($check > 1) $arr[$key]['serialNumber'] = "{$value['serialNumber']}_{$value['id']}";

			if($value['separatedId'] != null){
				$arr[$key]['serialNumber'] = "{$value['serialNumber']}_{$value['separatedId']}";
			}
		}

		return $arr;
	}

	
		public function getProductProcess($formGuid){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$cid = Session::$user["customerId"];
			Session::switchCustomer(0);	
			$PLANTCID = C("PLANT_CUSTOMERID");
			$miShareFrom = M("mishare_from");
			
			Session::switchCustomer($cid);
			$where["guid"]=$formGuid;
			$arr=$miShareFrom->where($where)->find();
			$path=$arr["path"];
			if($path){
			    $path.="-".$arr['id'];
			}else{
			    $path.=$arr['id'];
			}
	
			$path=str_replace("-", ",", $path);
			$whereres["mf.id"]= array('in',$path);
			
			$res=$miShareFrom->alias("mf")->field("wx.nickname,wx.headimgurl,mf.createTime")
			->join("wx_all_user as au  on au.id=mf.uid")
			->join("wx_".$PLANTCID."_user_weixin_info as wx  on wx.id=au.weixinUserId")
			->where($whereres)
			
			->order("instr('".$path."',mf.id)")->select();
			log::write('分享路径sql'.$miShareFrom->getLastSql());
						//echo $miShareFrom->getLastSql();
			if ($arr) {
	// 			Log::write("看看2015-02-02：".$ModuleProduct->getLastSql());
				Output::instance()->objArray($res);
			} else{
				Output::instance()->resultCode(code_success);
			}
			
			
		}
	
	
//获取单个商品订单详情
	public function getProductListByOrderId($oid,$order="number", $orderBy="desc", $start = 0, $limit = 10) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$ProductDetailModel = M("module_product_order_detail");
		Session::switchCustomer($cid);	
// 		$condition['fromCustomerId'] = array('eq',$cid);
		$condition['detail.oid'] = array('eq',$oid);
		$arr = $ProductDetailModel->alias('detail')
			->join("wx_module_product product ON detail.pid = product.id")
			->join("wx_module_product_order pOrder ON detail.oid = pOrder.id")
			->join("wx_module_product_order_detail_specification pSpec ON detail.id = pSpec.did")
			->where($condition)
			->field("pOrder.points,detail.id,product.id as pid,detail.name,detail.picUrl,detail.serialNumber,product.number,detail.discountedPrice AS buyDiscountPrice,detail.fixedPrice,
					detail.price,detail.freePrice,product.freeBuy,product.teambuy,product.teamPrice,detail.oid,detail.shareFromGuid,
					pOrder.payType,detail.count,  pSpec.firstSpecificName, pSpec.secSpecificName,detail
					.customizedInfo,detail.customizedName1,detail.customizedDescription1,
					detail.customizedName2,detail.customizedDescription2,detail.customizedName3,detail.customizedDescription3")
			->limit("$start, $limit")			
			->order("$order $orderBy")->select();
        foreach($arr as $k => $v){
			$arr[$k]['customizedInfo'] = json_decode($v['customizedInfo'],true);
//            $activityId = $v['activityId'];
//            $pid = $v['id'];
//            $levelId = $v['levelId'];
//            $where['dp.productId'] = $pid;
//            $where['disc.activId'] = $activityId;
//            $where['dp.deleted'] = 0;
//            $result = $dpModel
//                ->alias('dp')
//                ->join("wx_{$cid}_discount disc on dp.discountId = disc.id")
//                ->join("wx_{$cid}_activity activ on activ.id = disc.activId")
//                ->where($where)
//                ->field("dp.discountPrice")
//                ->find();
//            if($result['discountPrice']){
//                $discPrice = json_decode($result['discountPrice']);
//                if(gettype($discPrice) == 'array'){
//                    foreach($discPrice as $key => $value){
//                        if($levelId == $value->levelId){
//                            $arr[$k]['discountPrice'] = $value->discountPrice;
//                        }
//                    }
//                }else{
//                    $arr[$k]['discountPrice'] = $discPrice;
//                }
//            }
        }
		if ($arr) {
			$count =  $ProductDetailModel->alias('detail')
				->join("wx_module_product product ON detail.pid = product.id")
				->join("wx_module_product_order pOrder ON detail.oid = pOrder.id")
				->where($condition)
				->count();
			
			Output::instance()->objArray($arr, $count);
		} else {
			Output::instance()->resultCode(code_success);
		}
	}
	

	/**
	 * 获取订单详情
	 * @param $id	/订单id
	 * @param null $type	/订单类型
	 */
	public function getOrderById($id,$type=null){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);	
		$OrderModel = M("module_product_order");
		$OrderDetailModel = M("module_product_order_detail");
		$expressModel = M("module_express");
		$customeruserModel = M("customer_user");
		$sqlModel = M("");
        $depotModel = M("depot");
		$orderRefund_tab = M('module_product_order_refund');
		Session::switchCustomer($cid);
		$userWx_tab = M('user_weixin_info');
		$cuserId = session("id");
		$userAgent = $customeruserModel->where("id=$cuserId")->field("agent")->find();
		$condition['po.id'] = array('eq',$id);
		if($type == ORDER_TYPE_FORM){
			//分成等价格取表单设置时的价格,上一次分享人作为销售(密友)
			$order = $OrderModel->alias('a')
				->join('inner join wx_module_product_order_detail b on a.id=b.oid')
				->join('wx_micontent f on a.moduleId=f.id')
				->join('wx_'.$cid.'_user_weixin_info c on a.uId=c.userId')
				->join('wx_'.$cid.'_user d on a.uId=d.id')
				->join('wx_form e on b.pid=e.id')
				->join("wx_miyouquan g on a.qid=g.id")
				->where(['a.id'=>$id])
				->field('a.id, a.serialNumber, a.uId, a.qid,a.type, a.miUid, a.createTime, a.status, a.price, a.fullName,
			 a.phone, a.wxTransactionId, a.payType,b.customizedInfo, c.nickname,c.headimgurl, d.fullName as spareName,
			 d.phone as sparePhone,e.formName, e.type as isPay, e.payPrice, e.supplyPrice, e.platCut,
			 e.saleCut,f.title,g.name as qname,g.logo as qlogo')
				->find();
			//Log::write('tiaoshi:'.$OrderModel->getLastSql());
		}else{
		$order = $OrderModel->alias("po")
            ->field("info.headimgurl,g.nickName as refereeName,g.headImgUrl as refereeHeadImgUrl,h.nickName as parentRefereeName,h.headImgUrl as parentRefereeHeadImgUrl,po.*,c.name as qname,c.logo as qlogo,d.nickName as aname,d.headImgUrl as aheadImgUrl,e.phone as aphone,f.name as vname,po.couponName,po.couponMoney as money,cuser.fullName as channelName,f.supplierModule,i.id as orderChannelId,i.name as orderChannelName")
            ->join("wx_miyouquan c on po.qid=c.id")
            ->join("wx_".$cid."_user_weixin_info d on po.miUid=d.userId")
            ->join("wx_".$cid."_user_weixin_info g on po.refereeUid=g.userId")
            ->join("wx_".$cid."_user_weixin_info h on po.parentRefereeUid=h.userId")
            ->join("wx_all_user e on d.userId = e.id")
            ->join("wx_mivendor f on po.vId=f.id")
            ->join("wx_mivendor i on po.channelId=i.id")
            ->join("wx_customer_user cuser on po.fromCustomerId=cuser.customerId and cuser.agent='business'")
			->join("wx_" . $cid . "_user_weixin_info info on info.userId=po.uId")
            ->where($condition)->find();
            }
        // 如果有仓库, 查出仓库名称
        if ($order['depotid']) {
            $depotWhere['id'] = array('eq', $order['depotid']);
            $depotName = $depotModel->where($depotWhere)->getField('name');
            $order['depotName'] = $depotName;
        }

		$userWhere['userName']=array("eq",$order['fromUserName']);
		$datatime = date("Y-m-d H:i:s");
		$nowDate=date('Y-m-d H:i:s',strtotime("$datatime -2 day"));
		$userWhere['lastTime']=array("gt",$nowDate);
		$userInfo = $sqlModel->table("wx_".$cid."_user")->where($userWhere)->field("status")->find();
		if($userInfo&&$userInfo['status']<>'sharesubscribe'){
			$order['canSendMessage']=true;
		}
		$expressList = $expressModel->select();
		if ($order && ($type == null)) {
			$buyUserInfo = $sqlModel->table("wx_".$order['fromCustomerId']."_user_weixin_info")->where("openid='".$order['fromUserName']."'")->find();
			if($buyUserInfo){
				$order['nickname']=$buyUserInfo['nickname'];
				$order['headimgurl']=$buyUserInfo['headimgurl'];
			}
			$order['expressList']=$expressList;
			if ($order["type"] == type_buy) {
				Session::switchCustomer(0);	
				$refundModel = M("module_product_order_refund");
				Session::switchCustomer($cid);	
				$whereRefund["oid"] = $id;
				$whereRefund["status"] = status_ok;
				$refundMoney = $refundModel->where($whereRefund)->sum("refundPrice");
				if ($refundMoney) {
					$order["refundMoneySuccess"] = $refundMoney;
					$order["refundMoney"] = $order["price"] - $refundMoney;
				} else {
					$order["refundMoneySuccess"] = 0;
				}
				$whereHistory["oid"] = $id;
				$refundHistory = $refundModel->where($whereHistory)->sum("refundPrice");
				if ($refundHistory) {
					$refundSuccess = $refundMoney ? $refundMoney : 0;
				}
			}
			
			if (!isset($refundMoney) || $refundMoney == NULL) {
				$order["refundMoney"] = $order["price"];
			}
			
			// 一键支付的订单当前撤销不能修改退款金额
			$order["isRefundMoneyCanChange"] = true;
			if ($order["payType"] == ORDER_PAYTYPE_UPAY) {
				$order_date = date('Ymd',strtotime($order["createTime"]));
				$now_date = date('Ymd');
				if($now_date - $order_date == 0) {
					$order["isRefundMoneyCanChange"] = false;
				}
			} else if ($order["payType"] == ORDER_PAYTYPE_WXPAY) {
				// 获取是否是新微信支付，新微信支付不用显示密码
				$setting = R("CUser/getMallSetting");
				if (!$setting) {
					return false;
				}
				$order["isOld"] = $setting["isOld"];
			}

            $order['invoice'] = $this->getOrderInvoice($order);
			$order["userAgent"]=$userAgent["agent"];

			//取出订单的推荐人分成金额,积分信息
//			$orderDetail = $OrderDetailModel->where(['oid' => $order['id']])->field('isMiUserCut,isRefereeCut,isParentRefereeCut,pointConfig')->select();
            $orderDetail = $OrderDetailModel->where(['oid' => $order['id']])->field('isMiUserCut,isRefereeCut,isParentRefereeCut,pointConfig')->select();

            $order['buyerPoint'] = 0;
            $order['miPoint'] = 0;
            $order['preMiPoint'] = 0;
            $order['prePreMiPoint'] = 0;
            $order['recommenderPoint'] = 0;
            foreach ($orderDetail as $key => $value) {
                //<侯佳2018-04-08添加，返回积分获取情况>
                $arrPointConf = json_decode($value['pointConfig'], true);
                $order['buyerPoint'] += $arrPointConf['buyerPoint'];
                $order['miPoint'] += $arrPointConf['miPoint'];
                $order['preMiPoint'] += $arrPointConf['preMiPoint'];
                $order['prePreMiPoint'] += $arrPointConf['prePreMiPoint'];
                $order['recommenderPoint'] += $arrPointConf['recommenderPoint'];
                //</侯佳2018-04-08添加，返回积分获取情况>
                $order['isMiUserCut'] += $value['isMiUserCut'];
                $order['isRefereeCut'] += $value['isRefereeCut'];
                $order['isParentRefereeCut'] += $value['isParentRefereeCut'];
//				$pointConfig = json_decode($value['pointConfig']);
			}
//            var_dump($order);
            log::write($order);
			Output::instance()->object($order);
		} else if($order && $type==ORDER_TYPE_FORM){
			$order['expressList']=$expressList;
			if($order['miUid']){
				$saleInfo = $userWx_tab->where(['userId'=>$order['miUid']])->field('nickname, headimgurl')->find();
			}else{
				$saleInfo = $userWx_tab->where(['userId'=>$order['uId']])->field('nickname, headimgurl')->find();
			}
			//获取退款总额
			$refundMoney = $orderRefund_tab->where(['oid'=>$id, 'status'=>'ok'])->sum('refundPrice');
			$order['refundMoney'] = $refundMoney?$refundMoney:0;
			$order['saleInfo']['nickname'] = $saleInfo['nickname']?$saleInfo['nickname']:'';
			$order['saleInfo']['headimgurl'] = $saleInfo['headimgurl']?$saleInfo['headimgurl']:'';
			if($order['isPay'] == 1){
				if($order['status'] == ORDER_STATUS_PAYING || $order['status'] == order_status_refund || $order['status'] == ORDER_STATUS_REFUNDEDPART){
					$order['changeStatus'] = [
						['name'=>'已关闭','val'=>'closed']
					];
				}else if($order['status'] == order_status_delivering || $order['status'] == ORDER_STATUS_REFUNDING){
					$order['changeStatus'] = [
						['name'=>'已确认','val'=>'ok'],
						['name'=>'已取消','val'=>'cancel']
					];
				}else if($order['status'] == order_status_ok){
					$order['changeStatus'] = [
						['name'=>'已取消','val'=>'cancel']
					];
				}else if($order['status'] == order_status_cancel){
					$order['changeStatus'] = [
						['name'=>'已确认','val'=>'ok'],
						['name'=>'已关闭','val'=>'closed']
					];
				}else{
					$order['changeStatus'] = [];
				}
			}else{
				if($order['status'] == order_status_submission){
					$order['changeStatus'] = [
						['name'=>'已确认','val'=>'ok'],
						['name'=>'已关闭','val'=>'closed'],
						['name'=>'已取消','val'=>'cancel']
					];
				}else if($order['status'] == order_status_ok){
					$order['changeStatus'] = [
						['name'=>'已取消','val'=>'cancel']
					];
				}else if($order['status'] == order_status_cancel){
					$order['changeStatus'] = [
						['name'=>'已确认','val'=>'ok'],
						['name'=>'已关闭','val'=>'closed']
					];
				}else{
					$order['changeStatus'] = [];
				}
			}
			if($order['payType'] == 'wxpay'){
				$order['payTypeShow'] = '微信支付';
			}else if($order['payType'] == 'alipay'){
				$order['payTypeShow'] = '支付宝支付';
			}else{
				$order['payTypeShow'] = '其他';
			}
			$order['customizedInfo'] = json_decode($order['customizedInfo'], true);
			Output::instance()->object($order);
		}else{
			Output::instance()->resultCode(code_product_order_not_exist);
		}
			
		
	}
	
        public function getOrderRefundHistoryByOrderId($id,$start=0,$limit=10){
            $retVal = Session::init();
            if (!$retVal) {
                Output::instance()->resultCode(code_access_denied);
                return;
            }
            $cid = Session::$user["customerId"];
            Session::switchCustomer(0);
            $refundModel = M("module_product_order_refund");
            Session::switchCustomer($cid);
            $whereRefund["oid"] = $id;
            $whereRefund["status"] = status_ok;
            $arr = $refundModel->where($whereRefund)->limit($start,$limit)->order("createTime desc")->select();
            if($arr){
                $count = $refundModel->where($whereRefund)->count();
                Output::instance()->objArray($arr,$count);
            }else{
                Output::instance()->resultCode();
            }
        }
		private function getOrderInvoice($order) {
		if($order['invoiceTitle'] != NULL){
			$title = '';
			if($order['invoiceTitle'] == '1') $title = "公司({$order['invoiceTitleName']})";
			if($order['invoiceTitle'] == '2') $title = "个人({$order['invoiceTitleName']})";
			$invoice = "{$title}-{$order['invoiceMethodName']}-{$order['invoiceContentName']}";
		} else {
			$invoice = "";
		}
		return $invoice;
	}
	
	//批量核销验证码
	private static function cliamCode($oid){
//		$retVal = Session::init();
//		if (!$retVal) {
//			Output::instance()->resultCode(code_access_denied);
//			return;
//		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$orderModel = M("module_product_order");
		Session::switchCustomer($cid);
		$VerifyCode = M("module_verify_code");
		$orderInfo = $orderModel->where("id=$oid")->find();
		if($orderInfo['isVirtual']){
			$condition['oid']=array('eq',$oid);
			$data['isClaim'] = 1;
			$data['claimTime'] = date('Y-m-d H:i:s');
			$ret = $VerifyCode->where($condition)->save($data);
		}
	}
	/*
	 * 更新订单状态、卖家备注等信息
	 */
	public function updateOrderTipByOrderId($oid,$sellerNote=NULL,$sellerRemark=NULL,$status=NULL,
			$expressName = NULL, $expressNo = NULL, $needReturn = 0){
		if (!$needReturn) {
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
		}
		if ($status && ($status == 'ok'||$status==order_status_confirmsign)) {
			if($status==order_status_confirmsign){
				self::payForVendor($oid);
			}
			$num=self::myqupdateDividents($oid);
			if ($num) {
				R('Tuan/tuanBackMoney',array($oid));
				$result = $this->updateOrderByOrderId($oid, $sellerNote, $sellerRemark, $status,
					 $expressName, $expressNo);
				$redis = new RedisAPI();
				$redis->rPush('orderSuccess_log',$oid);

				if (!isset($result)) {
					return;
				}
				self::cliamCode($oid);
				if ($needReturn) {
					return true;
				}
			}
		}else {
			$result = $this->updateOrderByOrderId($oid, $sellerNote, $sellerRemark, $status,
				 $expressName, $expressNo);
			if (!isset($result)) {
				return;
			}
			if ($needReturn) {
				return true;
			}
		}
		$data["id"] = $oid;
        R('Log/add',array('wmxorder','','订单管理',op_update,'','修改订单信息'));
		Output::instance()->object($data);
	}

	public function updateOrderdeliverMiU($oid,$qid,$deliverMiUid){
		/** 1. 数据健壮性校验*/
		if ($oid == NULL && $deliverMiUid == NULL && $qid == NULL) {
			Output::instance()->resultCode();
			return;
		}

		/** 2. 实例化数据模型 */
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$ProductOrderModel = M("module_product_order");
		$miMallModel = M("mimall_user");
        $quanModel = M('miyouquan');
		Session::switchCustomer($cid);
		if($deliverMiUid == -1){
            $data['miUid'] = 0;
            $data['refereeUid'] = 0;
            $data['preRefereeUid'] = 0;
        }else {
            /** 查询重新指派注册好友的推荐人信息 */
            $miUidData = $miMallModel->where(['uId' => $deliverMiUid])->field('miUid,refereeUid,preRefereeUid')->find();
            /** 查询订单指派注册好友的推荐人信息 */
            $orderInfo = $ProductOrderModel->where(['id' => $oid])->field('miUid,refereeUid,parentRefereeUid,deliverMiUId')->find();
            if (!empty($orderInfo['miUid'])) {
                $data['miUid'] = $miUidData['miUid'];
            }
            if (!empty($orderInfo['refereeUid'])) {
                $data['refereeUid'] = $miUidData['refereeUid'];
            }
            if (!empty($orderInfo['preRefereeUid'])) {
                $data['parentRefereeUid'] = $miUidData['preRefereeUid'];
            }
            if (!empty($orderInfo['deliverMiUId'])) {
                $data['deliverMiUId'] = $miUidData['miUid'];
            }
        }
		$result = $ProductOrderModel->where(['id' => $oid])->save($data);
		if($result){
            R('Log/add',array('wmxorder','','订单管理',op_update,'','修改订单注册好友'));
            Output::instance()->resultCode();
            return;
		}else{
            Output::instance()->resultCode(code_sql_error);
            return;
		}
	}


    /**
     * 更新订单
     *
     * @param $oid
     * @param $sellerNote
     * @param $sellerRemark
     * @param $status
     * @param $expressName
     * @param $expressNo
     * $isFOrder: 是否是F2B中F供应商订单，F2B的订单只有B的订单才调用微信发货接口
     * @return bool|void
     * @modify lilei<LL_strive@163.com> 2017-04-21
     */
    public function updateOrderByOrderId($oid, $sellerNote, $sellerRemark, $status, $expressName, $expressNo)
    {
        /** 1. 数据健壮性校验*/
        if ($sellerNote == NULL && $sellerRemark == NULL && $status == NULL && $expressName == NULL && $expressNo == NULL) {
            Output::instance()->resultCode();
            return;
        }

        /** 2. 实例化数据模型 */
        $cid = Session::$user["customerId"];
        $userId = Session::$user["id"];
        Session::switchCustomer(0);
        $ProductOrderModel = M("module_product_order");
        Session::switchCustomer($cid);

//		$condition['fromCustomerId'] = $cid;

        // 外部接口会连续调用两次switchCustomer导致数据库前缀错误，需要传递customerId
        //$customerId = Session::$user["customerId"];
        //	$ProductOrderModel = M("module_product_order", 'wx_' . $customerId . '_');

        $condition['id'] = $oid;
        $order = $ProductOrderModel->where($condition)->find();
        if (!$order) {
            Output::instance()->resultCode(code_product_order_not_exist);
            return;
        }

        if ($status != NULL) {
            $data['status'] = $status;
            $data['updateTime'] = date("Y-m-d H:i:s");

            $payType = $order["payType"];
            if ($payType && ($payType == ORDER_PAYTYPE_WXPAY || $payType == ORDER_PAYTYPE_UPAY)
                && ($order["status"] == ORDER_STATUS_NOTSUBMIT || $order["status"] == ORDER_STATUS_PAYING
                    || $order["status"] == ORDER_STATUS_PAYINGCONFIRM)
            ) {
                Output::instance()->resultCode(code_product_order_status_change_invalid);
                return;
            }

            if ($payType && $payType == ORDER_PAYTYPE_WXPAY
                && (/*$status == order_status_delivered || */$status == order_status_deliveredtostore || $status == order_status_confirmsign)
            ) {
                $resNotify = $this->wxpayDeliveryNotify($order);
                if (!$resNotify) {
                    return;
                }
            }
        }

        if ($sellerNote != NULL) {
            $data['sellerNote'] = $sellerNote;
        }
        if ($status == order_status_delivered || $status == order_status_deliveredtostore) {
            $data['deliveryTime'] = date("Y-m-d H:i:s");
            $data['deliverCustomerUId'] = $userId;
        }
        if ($sellerRemark != NULL) {
            $data['sellerRemark'] = $sellerRemark;
        }

        if ($expressName != NULL) {
            $data['expressName'] = $expressName;
        }

        if ($expressNo != NULL) {
            $data['expressNo'] = $expressNo;
        }

        $result = $ProductOrderModel->where($condition)->save($data);

        if ($result !== false) {
            if (!$status || $order['status'] == $status) {
                return $result;
            }
            if ($status == order_status_delivered || $status == order_status_deliveredtostore) {
                self::payForVendor($oid);
            }
            if ($order['status'] == "refunding" && ($status == order_status_delivered || $status == order_status_ok)) {
                R('Product/deductProductInventory', array($oid));
                R('Product/addProductSalesCount', array($oid));
            }
            $params = new stdClass();
            $params->id = $oid;
            $params->userName = $order["fromUserName"];
            Module::callModule(module_handle_product, NULL, 'SendorderNotice', $params);
            return $result;
        } else {
            Output::instance()->resultCode(code_sql_error);
            return;
        }
    }

	//给供应商分成
	public function payForVendor($id){
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$ProductOrderModel = M("module_product_order");
		$accountVendor = M("account_vendor");
		$accountSupply = M("account_supply_chain");
		Session::switchCustomer($cid);
		$orderInfo = $ProductOrderModel->where("id=$id")->field("vendorAwardStatus")->find();
		if($orderInfo['vendorAwardStatus']){return;}
		$productList= $ProductOrderModel->alias("a")
			->join("inner join wx_module_product_order_detail b on a.id=b.oid")
			->join("wx_module_supply_chain c on a.supplyChainId=c.id")
			->join("wx_customer_user d on a.fromCustomerId=d.customerId and d.supplyRelation=2")
			->field("b.id,a.vId,b.isVendorCut,b.isChannelCut,b.sId,a.supplyChainId,b.oid,b.name,a.isChainOrder,
			d.fullName as channelName,d.id as channelId,a.serialNumber")
			->where("a.id=$id")
			->select();
		$ProductOrderModel->startTrans();
		foreach($productList as $key=>$value){
			$data = null;
			$data['module']='orderDetail';
			$data['type']=0;
			$data['deleted']=0;
			$data['createTime']=date("Y-m-d H:i:s");
			$data['oId']=$value['oid'];
			$data['vId']=$value['vId'];
			$data['moduleId']=$value['id'];
			$data['description']=$value['name'];
			$data['money']=$value['isVendorCut'];
			$data['serialNumber']=$value['serialNumber'];
			$accountResult = $accountVendor->add($data);
			if(!$accountResult){
				Log::write("供应商成分错误 ".$accountVendor->getLastSql());
				$ProductOrderModel->rollback();
				return;
			}else{
				unset($data['vId']);
				$coins =  $value['isVendorCut'];
				$query = "UPDATE wx_mivendor SET totalRevenue = totalRevenue + $coins,balance=balance+$coins WHERE id =".$value['vId'];
				$result = $ProductOrderModel->query($query);
			}
			if($result===false){
				Log::write("供应商成分错误 ".$ProductOrderModel->getLastSql());
				$ProductOrderModel->rollback();
				return;
			}
			if($value['isChainOrder']){
				$data['money']=$value['isChannelCut'];
				$data['supplyChainId']=$value['supplyChainId'];
				$data['channelId']=$value['channelId'];
				$data['channelName']=$value['channelName'];
				$accountResult = $accountSupply->add($data);
				if(!$accountResult){
					Log::write("供应链成分错误 ".$accountSupply->getLastSql());
					$ProductOrderModel->rollback();
					return;
				}else{
					$coins =  $value['isChannelCut'];
					$query = "UPDATE wx_supply_chain_balance SET totalRevenue = totalRevenue + $coins,balance=balance+$coins WHERE supplyChainId =".$value['supplyChainId']." and channelId=".$value['channelId'];
					$result = $ProductOrderModel->query($query);
				}
				if($result===false){
					Log::write("供应链成分错误 ".$ProductOrderModel->getLastSql());
					$ProductOrderModel->rollback();
					return;
				}
			}
		}
		$ProductOrderModel->where("id=$id")->setField("vendorAwardStatus",1);
		$ProductOrderModel->commit();
	}

		/**
	 * 发货时间限制:虚拟、服务类 24 小时内,实物类 72 小时内。请在收到支付通知后,按时发货,并使用发货通知接口将相关信息同步到微信后台。若 平台在规定时间内没有收到,将视作发货超时处理。
	 */
	private function wxpayDeliveryNotify($order) {
		$customerAndToken = WeixinApi::getCustomerAndAccessToken();
		if (!isset($customerAndToken)) {
			return false;
		}
		
// 		$customerId = Session::$user["customerId"];
// 		Session::switchCustomer(0);
// 		$uniUser = M("uni_user");
// 		$where["fromUserName"] = $order["fromUserName"];
// 		$where["customerId"] = $customerId;
// 		$fromUserName = $uniUser->where($where)->getField('fromUserName');
		$fromUserName = $order["fromUserName"];
// 		Session::switchCustomer($customerId);

//		$setting = R("CUser/getMallSetting");
        // 这里用下面这个替换上面内容, 目的是必过Session::init结果验证
		$setting = R("CUser/getMallSettingCopyForBoluopai");
		if (!$setting) {
			return false;
		}
		
		if ($setting["isOld"] == 0) {
			return true;
		}
		$wxPayHelper = new WxPayHelper();
		
		$notify = array();
		$notify["appid"] = $customerAndToken["appid"];
		$notify["openid"] = $fromUserName;
		$notify["transid"] = $order["wxTransactionId"];
		$notify["out_trade_no"] = $order["id"];
		$notify["deliver_timestamp"] = strval(time());
		$notify["deliver_status"] = "1";
		$notify["deliver_msg"] = "ok";
		$notify["app_signature"] = $wxPayHelper->get_biz_sign($notify, $setting["paySignKey"]);
		$notify["sign_method"] = "sha1";
		$notifyData = json_encode($notify);
// 		Log::write($notifyData);
		
		$url='https://api.weixin.qq.com/pay/delivernotify?access_token=' . $customerAndToken["token"];
		Log::write($url);
		$ch = curl_init($url) ;
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $notifyData);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($ch);
		curl_close($ch);
		Log::write($result);
		
		$result = json_decode($result);
		if ($result->errcode !== 0) {
			Log::write('order delivery notify error code:' . $result->errcode . ';msg:' . $result->errmsg);
			Output::instance()->resultCode(code_product_wx_delivery_notify_failed, $result->errmsg);
			return false;
		} else {
			return true;
		}
	}

	private function pointRefund($oid, $cid)
	{
		Session::switchCustomer(0);
		$ProductOrderModel = M("module_product_order");
		$userPointModel = M('module_user_point');
		$billModel = M('module_user_point_bill');
		$condition['a.id'] = $oid;
		$orderInfo = $ProductOrderModel->alias('a')
			->join('wx_module_product_order_detail d on d.oid = a.id')
			->where($condition)
			->field('a.*, d.name, d.pointConfig')
			->find();


		$pointConfig = json_decode($orderInfo['pointConfig'], true);
		if ($orderInfo['status'] == refund) {
			Output::instance()->object([
				'code' => 1,
				'msg' => '此订单已退款'
			]);
			return;
		}

		$points = $orderInfo['points'];
		$userId = $orderInfo['uId'];
		$ProductOrderModel->startTrans();
		//增加积分
		$pointInfo = $userPointModel->where(['cid' => $cid, 'userId' => $userId])->find();
		//修改积分余额
		$ProductOrderModel->startTrans();
		$data = [
			'pointBalance' => $pointInfo['pointBalance'] + $points,
			'totalPoint' => $pointInfo['totalPoint'] + $points,
			'updateTime' => date('Y-m-d H:i:s', time())
		];
		$pointRes = $userPointModel->where(['cid' => $cid, 'userId' => $userId])->save($data);

		//增加退款记录
		$billData = [
			'cid' => $cid,
			'userId' => $userId,
			'module' => 'order',
			'moduleId' => $pointInfo['serialNumber'],
			'channel' => '积分订单退款',
			'description' => '商品名称：' . $orderInfo['name'],
			'type' => POINT_TYPE_IN,
			'number' => $points,
			'pointSchemeId' => $pointConfig['pointSchId'],
			'pointSchemeName' => $pointConfig['schemeName'],
			'createTime' => date('Y-m-d H:i:s', time())
		];
		$billRes = $billModel->add($billData);

		//修改订单状态
		$orderRes = $ProductOrderModel->where(['id' => $oid])->setField('status', 'refund');
		if (is_numeric($pointRes) && is_numeric($billRes) && is_numeric($orderRes)) {
			$ProductOrderModel->commit();
			Output::instance()->object([
				'code' => 0,
				'msg' => '退款成功'
			]);
		} else {
			$ProductOrderModel->rollback();
			Output::instance()->object([
				'code' => 1,
				'msg' => '退款失败'
			]);
		}

	}

	/*
	 * 订单退款
	 * $refundMoney:退款金额，单位元
	 */
	public function orderRefund($oid, $refundMoney, $refundPwd = '') {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);	
		$ProductOrderModel = M("module_product_order");
		$quan_user = M("quan_user");
		$miu_statistics = M("miu_statistics");
		$salesource_statistics = M("salesource_statistics");
		$condition['id'] = $oid;
		$orderInfo = $ProductOrderModel->where($condition)->find();
		if (!$orderInfo['serialNumber']) {
			Output::instance()->resultCode(code_product_order_not_exist);
			return;
		}


		//<侯佳添加于2018-01-11，积分订单退款>
		if ($orderInfo['type'] == ORDER_TYPE_POINT) {
			$this->pointRefund($oid, $cid);
			return;
		}
		//</侯佳添加于2018-01-11，积分订单退款>
		// 由于有拆单的问题，所以订单总金额需要通过订单编号查询
		$orderInfo["tempSerialNumber"]?$whereBh['tempSerialNumber'] = $orderInfo["tempSerialNumber"]:$whereBh['serialNumber'] = $orderInfo["serialNumber"];
		$order = $ProductOrderModel->where($whereBh)->field("sum(price) as price, payType, wxTransactionId, serialNumber, createTime,tempSerialNumber,purseMoney,merchantMode")->find();
		if (!$order) {
			Output::instance()->resultCode(code_product_order_not_exist);
			return;
		}
		$payType = $order["payType"];
		if ($payType == NULL) {
			Output::instance()->resultCode(code_product_pay_type);
			return;
		}
		
		$RefundModel = M("module_product_order_refund");
        $refwhere["oid"] = $oid;
        $refwhere["status"] = array("eq", status_ok);
        $totalRefund = $RefundModel->where($refwhere)->sum("refundPrice");
        !$totalRefund?$totalRefund=0:"";

		// 查找是否有退款失败记录
		$whereRefund["oid"] = $oid;
		$whereRefund["refundPrice"] = $refundMoney;
		$whereRefund["status"] = array(array("eq", status_error), array("exp", "IS NULL"), "OR");
		$refund = $RefundModel->where($whereRefund)->find();
		if (!$refund || $payType == ORDER_PAYTYPE_UPAY) {
			$data["oid"] = $oid;
			$data["wxTransactionId"] = $order["wxTransactionId"];
			$data["totalPrice"] = $order["price"];
			$data["refundPrice"] = $refundMoney;
			$data["createTime"] = date("Y-m-d H:i:s");
			if ($payType == ORDER_PAYTYPE_UPAY || $payType == ORDER_PAYTYPE_AINONGPAY) {
				$refundTransactionId = date('ymdHis').rand(1000,9999);
				$data["refundTransactionId"] = $refundTransactionId;
			}
			$refundId = $RefundModel->add($data);
			if (!$refundId) {
				Output::instance()->resultCode(code_sql_error);
				return;
			}
		} else {
			$refundId = $refund["id"];
			$refundTransactionId = $refund["refundTransactionId"];
		}

		//
        if($refundMoney+$totalRefund>$order["price"]){
		    Output::instance()->resultCode(1,"超出订单金额！");
		    return;
        }
        //rmb支付金额
		$orderPrice = ($order["price"]-$order["purseMoney"])* 100;
        //可退rmb金额
        $payPrice = $order["price"]-$order["purseMoney"]-$totalRefund;
        if($payPrice<=0){//rmb是不是都退了
            $refundMoney=0;
        }else if($refundMoney<=$payPrice){
            $refundMoney = $refundMoney*100;
        }else{
            $refundMoney=$payPrice*100;
        }
        if($refundMoney>0){
            $order["tempSerialNumber"]?$serialNumber = $order["tempSerialNumber"]:$serialNumber = $order["serialNumber"];
            switch ($payType) {
                case ORDER_PAYTYPE_WXPAY:
                    R('Wxpay/wxpayRefund', array($order["wxTransactionId"], $refundId, $orderPrice,
                        $refundMoney, $refundPwd, $oid, $serialNumber,$order['merchantMode']));
                    break;
                case ORDER_PAYTYPE_TENPAY:
                    R('Tenpay/tenpayRefund', array($oid, $serialNumber, $refundId, $orderPrice, $refundMoney,"435494"));
                    break;
                case ORDER_PAYTYPE_UPAY:
                    R('Upay/upayRefund', array($oid, $serialNumber, $refundTransactionId, $refundId,
                        $orderPrice, $refundMoney, $order["createTime"]));
                    break;
                case ORDER_PAYTYPE_DELIVERIY_PAY:
                    $ProductOrderModel->where($condition)->setField("status",order_status_refund);
                    Output::instance()->resultCode();
                    break;
                case "alipay":
                    R('Alipay/orderRefund', array($cid,$order["wxTransactionId"], $refundId,
                        $refundMoney, $oid));
                    Output::instance()->resultCode();
                    break;
				case ORDER_PAYTYPE_AINONGPAY:
					R('AiNongpay/refundOrderAiNongPay', array($cid,$serialNumber, $refundId,
						$refundMoney, $oid,$refundTransactionId));
					Output::instance()->resultCode();
					break;
                default:
                    Output::instance()->resultCode(code_product_pay_type);
                    break;
            }
        }else{
            Session::switchCustomer($cid);
            ProductOrder::updateOrderRefund($oid,$refundId,true,null);
            Output::instance()->resultCode();
        }
        Session::switchCustomer($cid);
	}

	/**
	 * 统计退款减少
	 * @param $oid
	 * @param $refundMoney
	 */
	public function refundStatistics($oid='',$refundMoney=''){
		if(empty($oid) || empty($refundMoney)){
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$ProductOrderModel = M("module_product_order");
		$quan_user = M("quan_user");
		$miu_statistics = M("miu_statistics");
		$salesource_statistics = M("salesource_statistics");
		Session::switchCustomer($cid);
		$condition['id'] = $oid;
		$orderInfo = $ProductOrderModel->where($condition)->find();
		$userInfo = $quan_user->alias('a')->where(['a.uId' => $orderInfo["uId"],'b.cId' => $orderInfo['fromCustomerId'],'deleted' => 0])->join('wx_miyouquan as b on a.qid=b.id')->field('qid')->find();
		if(!empty($userInfo)){
			$miu_statistics->where(['uid' => $orderInfo["uId"],'cid' => $orderInfo['fromCustomerId']])->setDec('orderPrice', $refundMoney);
		}
		if(!empty($userInfo['saleSource'])){
			$salesource_statistics->where(['uid' => $orderInfo["uId"],'cid' => $orderInfo['fromCustomerId']])->setDec('orderPrice', $refundMoney);
		}
	}

	/**
	 * [myqupdateDividents 订单成功后分成分配]
	 * @param  [type] $oid [订单id]
	 * @return [type]      [description]
	 */
	public function myqupdateDividents($oid){
		/*$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}*/
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$ProductOrderModel = M("");
		$ProductOrderDetailModel = M('module_product_order_detail');
		$userPointModel = M('module_user_point');
		$pointBillModel = M('module_user_point_bill');
		$miacAdminModel = M("system_income");
		$orderDeliverModel = M("module_product_order_deliver");
		$quanModel = M("miyouquan");
		Session::switchCustomer($cid);
        $pointModel = D('Point', 'Logic');

		$oldwhere['id'] = $oid;
		$delwhere['oid'] = $oid;
		$oldarr = $ProductOrderModel->table('wx_module_product_order')->alias("a")
			->join("wx_quan_user c on a.miUid=c.uid and c.qid=a.qId")
//			->join("wx_all_user d on d.id=a.miUid")
			->join("wx_".$cid ."_user_weixin_info d on d.userId=a.miUid")
			->where("a.id=$oid")
			->field('a.uId,a.recommenderId,a.type,a.partnerAwardStatus,a.isActivity,a.price,a.status,a.qId,a.miUid,a.miAward,a.lordAward,a.module,a.moduleId,
			a.vId,a.createTime,a.updateTime,a.fromUserName,a.fromCustomerId,a.serialNumber,
			a.refereeUid,d.nickName as fullName,c.teamId,a.parentRefereeUid,a.deliverMiUId')
			->find();
		if($oldarr['isActivity']){
			$oldorderarr['status'] = order_status_confirmsign;
		}else{
			$oldorderarr['status'] = 'ok';
		}
		if($oldarr['partnerAwardStatus']){
			//此时订单之前已经完成分成
			$result=$ProductOrderModel->table('wx_module_product_order')->where($oldwhere)->save($oldorderarr);
			if (is_numeric($result)) {
				return true;
			} else {
				return false;
			}
		}

		$status = $oldarr['status'];
		$deliveryTime = $oldarr["updateTime"];
		$orderTime = $oldarr["createTime"];
		$serialNumber = $oldarr["serialNumber"];
		$fromCustomerId = $oldarr["fromCustomerId"];
		$fromUserName = $oldarr["fromUserName"];
			$ProductOrderModel->startTrans();
			if($oldarr["teamId"]){
				$sql = "UPDATE wx_quan_team SET totalOrder=totalOrder+1,totalSales=totalSales+".$oldarr["price"]." WHERE id=".$oldarr["teamId"];
				$result = $ProductOrderModel->query($sql);
				Log::write("写入团队表有误:".$ProductOrderModel->getLastSql());
				if($result===false){
					$ProductOrderModel->rollback();
					return false;
				}
			}
			//给密友增加订单数和销售额
			if($oldarr["qId"]&&$oldarr["miUid"]){
				$sql = "UPDATE wx_quan_user SET totalOrder=totalOrder+1,totalSales=totalSales+".$oldarr["price"]." WHERE qid=".$oldarr["qId"]." and uid=".$oldarr["miUid"];
				$result = $ProductOrderModel->query($sql);
				Log::write("写入quan_user表有误:".$ProductOrderModel->getLastSql());
				if($result===false){
					$ProductOrderModel->rollback();
					return false;
				}
			}
			$quanInfo = $quanModel->where("id=".$oldarr["qId"])->find();
			$detailarr = $ProductOrderModel->table('wx_module_product_order_detail')->alias("a")
				->where($delwhere)->select();
			$agentInfo = $ProductOrderModel->table("wx_vendor_agent")->where("FIND_IN_SET(".$oldarr['vId'].",vendors)")->find();

			//LP修改 查询订单的cid对应user_weixin_info表二级、三级推荐人昵称写入收入
			Session::switchCustomer($fromCustomerId);
			$userWxInfoModel = M("user_weixin_info");
			Session::switchCustomer($cid);

        $userId = $oldarr['uId'];
        $miId = $oldarr['miUid'];
        $preMiId = $oldarr['refereeUid'];
        $prePreMiId = $oldarr['parentRefereeUid'];
        $recommenderId = $oldarr['recommenderId'];
			foreach ($detailarr as $k => $v) {
				switch($v['type']){
					case ORDER_TYPE_FORM:
						$channel = '营销订单';
						$description = $v['name'];
						$orderType = 'formOrder';
						break;
					default:
						$channel = '商品订单';
						$description = $v['name'];
						$orderType = 'order';
						break;
				}

                //<侯佳2018-06-14修改，分配积分>
                $arrConfig = json_decode($v['pointConfig'], true);
                /*给购买人积分*/
                if (!empty($arrConfig['buyerPoint']) && $userId) {
                    $buyerRes = $pointModel->addPoint(
                        $userId,
                        $arrConfig['buyerPoint'],
						$orderType,
                        $serialNumber,
						$channel,
						$description,
                        $arrConfig['pointSchId'],
                        $arrConfig['schemeName']
                    );
                }

                /*给注册好友积分*/
                if (!empty($arrConfig['miPoint']) && $miId) {
                    $miRes = $pointModel->addPoint(
                        $miId,
                        $arrConfig['miPoint'],
						$orderType,
                        $serialNumber,
						$channel,
						$description,
                        $arrConfig['pointSchId'],
                        $arrConfig['schemeName']
                    );
                }

                /*给注册好友推荐人积分*/
                if (!empty($arrConfig['preMiPoint']) && $preMiId) {
                    $preMiRes = $pointModel->addPoint(
                        $preMiId,
                        $arrConfig['preMiPoint'],
						$orderType,
                        $serialNumber,
						$channel,
						$description,
                        $arrConfig['pointSchId'],
                        $arrConfig['schemeName']
                    );
                }

                /*给注册好友推荐人的推荐人积分*/
                if (!empty($arrConfig['prePreMiPoint']) && $prePreMiId) {
                    $prePreMiRes = $pointModel->addPoint(
                        $prePreMiId,
                        $arrConfig['prePreMiPoint'],
						$orderType,
                        $serialNumber,
						$channel,
						$description,
                        $arrConfig['pointSchId'],
                        $arrConfig['schemeName']
                    );
                }

                /*给购买人的锁定人积分*/
                if (!empty($arrConfig['recommenderPoint']) && $recommenderId) {
                    $recommenderRes = $pointModel->addPoint(
                        $recommenderId,
                        $arrConfig['recommenderPoint'],
						$orderType,
                        $serialNumber,
						$channel,
                        $description,
                        $arrConfig['pointSchId'],
                        $arrConfig['schemeName']
                    );
                }
                //</侯佳2018-06-14修改，分配积分>
				$data = '';
				$data['isPlatCut']=$v['isPlatCut'];
				$data['isVendorCut']=$v['isVendorCut'];
				$data['isAgentCut']=$v['isAgentCut'];
				$data['isLordCut'] = $v['isLordCut'];
				$data['isMiUserCut'] = $v['isMiUserCut'];
				$data['isRefereeCut']=$v['isRefereeCut'];
				$data['isParentRefereeCut']=$v['isParentRefereeCut'];
                $data['isUserCut']=$v['isUserCut'];
					// 写入密友圈角色金额详情
					$prowhere['id'] = $v['pid'];
					$miacarr = '';
					$miacarr['module'] = 'orderDetail';
					$miacarr['moduleId'] = $v['id'];
					$miacarr['description'] = $v['name'];
					$miacarr['createTime'] = date("Y-m-d H:i:s");
					$miacarr['deleted'] = 0;
					$miacarr['type'] = 0;
					if($agentInfo['id']){
						$miacarr['agentId']=$agentInfo['id'];
						$miacarr['oId']=$oid;
						$miacarr['money'] = $data['isAgentCut'];
						//在供应商收入表增加一条记录
						$result = $ProductOrderModel->table('wx_account_agent')->add($miacarr);
						Log::write("写入代理商金额错误:".$ProductOrderModel->getLastSql());
						if ($result === false) {
							$ProductOrderModel->rollback();
							return false;
						}else{
							unset($miacarr['agentId']);
							unset($miacarr['oId']);
						}
						$coins =  $data['isAgentCut'];
						//更新供应商总收入及账户余额
						$query = "UPDATE wx_vendor_agent SET totalRevenue = totalRevenue + $coins,balance=balance+$coins WHERE id =".$agentInfo['id'];
						$result = $ProductOrderModel->query($query);
						Log::write("写入代理商分成金额:".$ProductOrderModel->getLastSql());
						if ($result === false) {
							$ProductOrderModel->rollback();
							return false;
						}
					}
					$miacarr['vId'] = $oldarr['vId'];
					$miacarr['vsistId'] = $v['visitId'];
					$miacarr['shareFromGuid'] = $v['shareFromGuid'];
					$miacarr['sId'] = $v['sId'];
					$miacarr['quanId'] = $oldarr['qId'];
					$miacarr['uId'] = $oldarr['miUid'];
					$miacarr['money'] = $data['isPlatCut'];
					//平台收入支出表中增加一条记录
					$result = $ProductOrderModel->table('wx_miaccount_system')->add($miacarr);
					Log::write("写入平台角色金额错误:".$ProductOrderModel->getLastSql());
					if ($result === false) {
						$ProductOrderModel->rollback();
						return false;
					}
					//给主公分成
					if($oldarr['qId']){
						$miacarr['money'] = $data['isLordCut'];
						//主公收入表增加一条记录
						$result = $ProductOrderModel->table('wx_miaccount_lord')->add($miacarr);
						Log::write("写入主公角色金额错误:".$ProductOrderModel->getLastSql());
						if ($result === false) {
							$ProductOrderModel->rollback();
							return false;
						}
						// 写入主公分成金额
						$oqid = $oldarr['qId'];
						$coins = $data['isLordCut'];
						$query = "UPDATE wx_miyouquan SET coins = coins + $coins,totalRevenue=totalRevenue+$coins WHERE id =$oqid";
						$result = $ProductOrderModel->query($query);
						// 如果主公分成设置是0，也选择通过
						Log::write("写入主公分成金额:".$ProductOrderModel->getLastSql());
						if ($result === false) {
							$ProductOrderModel->rollback();
							return false;
						}
					}
				    //给推荐人分成
					if($oldarr['miUid']){
						$miacarr['money'] = $data['isMiUserCut'];
						//密友分成表增加一条记录
						$result= $ProductOrderModel->table('wx_miaccount_friend')->add($miacarr);
						Log::write("写入密友角色金额错误:".$ProductOrderModel->getLastSql());
						if ($result === false) {
							$ProductOrderModel->rollback();
							return false;
						}
						// 写入密友分成金额
						$uqid = $oldarr['qId'];
						$uuid = $oldarr['miUid'];
						$miCoins = $data['isMiUserCut'];
						$query = "UPDATE wx_quan_user SET miCoins = miCoins + $miCoins,totalRevenue=totalRevenue+$miCoins WHERE qid = $uqid AND uid  = $uuid";
						$result = $ProductOrderModel->query($query);
						Log::write("写入密友分成金额:".$ProductOrderModel->getLastSql());
						if ($result === false) {
							$ProductOrderModel->rollback();
							return false;
						}
					}
					//给二级推荐人分成
					if($oldarr['refereeUid']&&$data['isRefereeCut']>0){
						$miacarr['uId'] = $oldarr['refereeUid'];
						$miacarr['money'] = $data['isRefereeCut'];
						$nickName = $userWxInfoModel->where(['userId' => $oldarr['miUid']])->getField('nickName');	//获取推荐人昵称写入上级推荐人收入明细
						$miacarr['description'] = $nickName .'-'. $v['name'];
						if($miacarr['uId']) {
							$result = $ProductOrderModel->table('wx_miaccount_friend')->add($miacarr);
							Log::write("写入密友角色推荐金额错误:" . $ProductOrderModel->getLastSql());
							if ($result === false) {
								$ProductOrderModel->rollback();
								return false;
							}
						}
						// 写入密友二级销售分成金额
						$uqid = $oldarr['qId'];
						$uuid = $oldarr['refereeUid'];
						$miCoins = $data['isRefereeCut'];
						if($uuid){
							$query = "UPDATE wx_quan_user SET miCoins = miCoins + $miCoins,totalRevenue=totalRevenue+$miCoins WHERE qid = $uqid AND uid  = $uuid";
							$result = $ProductOrderModel->query($query);
							Log::write("写入密友推荐分成金额:".$ProductOrderModel->getLastSql());
							if ($result === false) {
								$ProductOrderModel->rollback();
								return false;
							}
						}
					}
					//给三级推荐人分成
					if($oldarr['parentRefereeUid']&&$data['isParentRefereeCut']>0){
						$miacarr['uId'] = $oldarr['parentRefereeUid'];
						$miacarr['money'] = $data['isParentRefereeCut'];
						$nickName = $userWxInfoModel->where(['userId' => $oldarr['refereeUid']])->getField('nickName');	//获取二级推荐人昵称写入三级推荐人收入明细
						$miacarr['description'] = $nickName .'-'. $v['name'];
						if($miacarr['uId']) {
							$result = $ProductOrderModel->table('wx_miaccount_friend')->add($miacarr);
							Log::write("写入密友角色二级推荐金额错误:" . $ProductOrderModel->getLastSql());
							if ($result === false) {
								$ProductOrderModel->rollback();
								return false;
							}
						}
						// 写入密友三级销售分成金额
						$uqid = $oldarr['qId'];
						$uuid = $oldarr['parentRefereeUid'];
						$miCoins = $data['isParentRefereeCut'];
						if($uuid){
							$query = "UPDATE wx_quan_user SET miCoins = miCoins + $miCoins,totalRevenue=totalRevenue+$miCoins WHERE qid = $uqid AND uid  = $uuid";
							$result = $ProductOrderModel->query($query);
							Log::write("写入密友二级推荐分成金额:".$ProductOrderModel->getLastSql());
							if ($result === false) {
								$ProductOrderModel->rollback();
								return false;
							}
						}
					}

                //下单人分成
                if($data['isUserCut']>0){
                    $miacarr['money'] = $data['isUserCut'];
                    $miacarr['uId'] = $userId;
                    //密友分成表增加一条记录
                    $result= $ProductOrderModel->table('wx_miaccount_friend')->add($miacarr);
                    Log::write("写入密友角色金额错误:".$ProductOrderModel->getLastSql());
                    if ($result === false) {
                        $ProductOrderModel->rollback();
                        return false;
                    }
                    // 写入密友分成金额
                    $uqid = $oldarr['qId'];
                    $miCoins = $data['isUserCut'];
                    $query = "UPDATE wx_quan_user SET miCoins = miCoins + $miCoins,totalRevenue=totalRevenue+$miCoins WHERE qid = $uqid AND uid  = $userId";
                    $result = $ProductOrderModel->query($query);
                    Log::write("写入下单人分成金额:".$ProductOrderModel->getLastSql());
                    if ($result === false) {
                        $ProductOrderModel->rollback();
                        return false;
                    }
                }
					// 写入平台分成金额
					$income = $data['isPlatCut'];
					$oldincome = $miacAdminModel->field('id')->find();
					$tempoid =$oldincome['id'];
					$indata['income'] = $income;
					$indata['updateTime'] = date("Y-m-d H:i:s");
					$dtime = date("Y-m-d H:i:s");
					if ($oldincome) {
						$query = "UPDATE wx_system_income SET income = income + $income, updateTime = '$dtime'  WHERE id = $tempoid";
						$result = $ProductOrderModel->query($query);
					}else{
						$result = $ProductOrderModel->table('wx_system_income')->add($indata);
					}
					Log::write("写入平台分成金额:".$ProductOrderModel->getLastSql());
					if ($result === false) {
						$ProductOrderModel->rollback();
						return false;
					}
					if(!empty($oldarr["deliverMiUId"]) && $oldarr["deliverMiUId"] != 0){
                        //添加申请补货记录
                        $deliverInfo = $ProductOrderModel->table("wx_module_product_order_detail_specification")->where(['did' => $v['id']])->field('firstSpecificName,secSpecificName')->find();
                        $deliverInfo['pid'] = $v['pid'];
                        $deliverInfo['uid'] =  $oldarr["deliverMiUId"];
                        $deliverInfo['cid'] =  $oldarr["fromCustomerId"];
                        $deliverInfo['type'] =  $oldarr["type"];
                        $count = $orderDeliverModel->where($deliverInfo)->count();
                        if($count){
                            $orderDeliverModel->where($deliverInfo)->setInc('count', $v['count']);
                            $orderDeliverModel->where($deliverInfo)->setField('name', $v['name']);
                        }else{
                            //取商品图片
                            $productUrl = $ProductOrderModel->table('wx_module_product')->where(['id'=>$deliverInfo['pid']])->getField('picUrl');
                            $deliverInfo['productName'] = $v['name'];
                            $deliverInfo['productUrl'] = $productUrl;
                            $deliverInfo['count'] = $v['count'];
                            $deliverInfo['uid'] = $oldarr["deliverMiUId"];
                            $deliverInfo['cid'] = $oldarr["fromCustomerId"];
                            $deliverInfo['type'] = $oldarr["type"];
                            $deliverInfo['vid'] = $oldarr["vId"];
                            $orderDeliverModel->add($deliverInfo);
                        }
                    }
			}
			$oldorderarr['updateTime'] = date("Y-m-d H:i:s");
			$oldorderarr['completionTime'] = date("Y-m-d H:i:s");
			$oldorderarr['partnerAwardStatus']=1;
			$result=$ProductOrderModel->table('wx_module_product_order')->where($oldwhere)->save($oldorderarr);
			Log::write("更改订单状态:".$ProductOrderModel->getLastSql());
			if ($result === false) {
				$ProductOrderModel->rollback();
				return false;
			}
			$ProductOrderModel->commit();
				self::SendDeliveredNotice($oid,$fromCustomerId,$deliveryTime,$orderTime,$serialNumber,$fromUserName);
				self::taskOrderCallback($oid,$fromCustomerId);
				return true;

	}
	//任务订单处理
	public function taskOrderCallback($oid,$cid){
		Session::switchCustomer(0);
		$orderModel = M("module_product_order_detail");
		$taskModel = M("module_user_task");
		Session::switchCustomer($cid);
		$where['a.oid'] = array("eq",$oid);
		$where['a.taskModel'] = array("eq",1);//修改筛选条件，之前是在商品表中取商品是否开启任务模式，现在是在订单详情表里面判断该订单是否包含任务【mh修改于2018-04-09】
		$orderInfo = $orderModel->alias("a")
			->join("inner join wx_module_product b on a.pid = b.id")
			->join("inner join wx_module_product_order c on a.oid=c.id")
            ->join("inner join wx_".$cid."_user d on c.uid=d.id")
			->where($where)
			->field("a.taskInfo,a.oid,a.pid,b.picUrl1,c.uid,c.fromCustomerId,d.userName")//修改取值，之前是在商品表中取json，现在是在订单详情表里面取任务信息【mh修改于2018-04-09】
			->select();
		//mh修改订单任务处理逻辑，之前是只查询出来一个订单中的商品，现在是全部查询出来循环处理20180312
		foreach ($orderInfo as $key=>$value){
            $where_data = null;
            $where_data['cId'] = $value['fromCustomerId'];
            $where_data['oid'] = $value['oid'];
            $where_data['pid'] =  $value['pid'];
            $where_data['uid'] = $value['uid'];
            $taskInfo = $taskModel->where($where_data)->find();
			log::write('任务模块查询：'.$taskModel->getLastSql());
            if ($taskInfo) {
                continue;
            }else{
                $data = null;
                $data['cId'] = $value['fromCustomerId'];
                $data['oid'] = $value['oid'];
                $data['pid'] =  $value['pid'];
                $data['uid'] = $value['uid'];
                //修改取值方式，之前是在商品表中取json，现在是在订单详情表里面取任务信息【mh修改于2018-04-09】
                // $configJson = json_decode($value['json'],true);
                $data['configJson'] = $value['taskInfo'];
                $taskInfo =  json_decode($value['taskInfo'],true);
                $data['taskName'] = $taskInfo['taskName'];
                $picUrl = json_decode($value['picUrl1'],true);
                if($picUrl&&$picUrl[1]){
                    $data['proImg'] =  $picUrl[1]['picUrl'];
                }else if($picUrl){
                    $data['proImg'] =  $picUrl[0]['picUrl'];
                }
                $data['createTime'] = date("Y-m-d H:i:s");
                $data['updateTime'] = date("Y-m-d H:i:s");
                $taskId = $taskModel->add($data);
                Log::write("分配任务  ".$taskModel->getLastSql());

                //孟慧修改于20180409，用于任务分配之后添加发送模板消息
                $url = WeixinApi::getDomainName();
                $tempUrl = $url['SERVER_HOST']. "call.html?customerId=" . $cid .
                    "&module=productTask&method=index&params=%7B%22id%22%3A$taskId,%22h%22%3A%22progressList%22%7D";
                $tempUrl = urlencode($tempUrl);
                $sendData['first'] = array('value'=> '您有待开启任务','color'=>'#3f960b');
                $sendData['keyword1'] = array('value'=> $taskInfo['taskName'],'color'=>'#173177');
                $sendData['keyword2'] = array('value'=> '未开启','color'=>'#173177');
                $sendData['keyword3'] = array('value'=> "未开启",'color'=>'#173177');
                $sendData['remark'] = array('value'=>'点击进入任务' ,'color'=>'#0751f8');
                TemplateMessage::send( $value['userName'],$cid,'taskExamine',$tempUrl,$sendData);
                Log::write("分配任务后发送模板消息");
            }
        }
	}
	//商品复制
	public function copyProductById($id,$customerId=null,$isSelf=0){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$productModule = M("module_product");
		$specModel = m('module_product_specification');
		$productSpecName = M("module_product_specification_name");
		$productSpecGroup = M("module_product_specification_group");
		$shareBaseModel=M("mishare");
		$ProductTagListModel = M("module_product_tag_list");
		$ProductTagModel = M("module_product_tag");
		$shareMaterModel=M("mishare_material");
		Session::switchCustomer($cid);
		$time = date("Y-m-d H:i:s");
		$productInfo = $productModule->where("id=".$id)->find();
		unset($productInfo["id"]);
		unset($productInfo['salesCount']);
		unset($productInfo['isChainPro']);
		unset($productInfo['supplyChainId']);
		unset($productInfo['supplyProId']);
		if($isSelf){
			unset($productInfo['vId']);
			$productInfo['inventory']=0;
			unset($productInfo['inventoryCount']);
		}else{
			unset($productInfo['serialNumber']);
		}
		$customerId?"":$customerId=$cid;
		$cid = $productInfo['fromCustomerId'];
		$productInfo['fromCustomerId']=$customerId;
		$productInfo["createTime"]=$time;
		$productInfo["updateTime"]=$time;
		$newProductId = $productModule->add($productInfo);
		if($productInfo['supportSpecification']){
			$groupWhere['fromCustomerId']=array("eq",$cid);
			$groupWhere['pid'] = array("eq",$id);
			$groupInfo = $productSpecGroup->where($groupWhere)->select();
			foreach($groupInfo as $i=>$group){
				$groupData = null;
				$groupData['groupName']=$group['groupName'];
				$groupData['fromCustomerId']=$customerId;
				$groupData['pid']=$newProductId;
				$groupData['updateTime']=date("Y-m-d H:i:s");
				$groupData['spetype']=0;
				$groupId = $productSpecGroup->add($groupData);
				$nameList = $productSpecName->where("groupId=".$group['id'])->select();
				foreach($nameList as $j=>$name){
					$nameData=null;
					$nameData['groupId']=$groupId;
					$nameData['specificationName']=$name['specificationName'];
					$nameData['updateTime']=date("Y-m-d H:i:s");
					$nameData['specificationUrl']=$name['specificationUrl'];
					$nameId= $productSpecName->add($nameData);
					$specArray[$name['specificationName']]=$nameId;
				}
			}
			$productSpecList = $specModel->where("pid=$id")->select();
			foreach($productSpecList as $k=>$spec){
				unset($spec['id']);
				if(!$isSelf){
					unset($spec['serialNumber']);
				}
				$spec['pid']=$newProductId;
				$spec['firstSpecificId']=$specArray[$spec['firstSpecificName']];
				$spec['secSpecificId']=$specArray[$spec['secSpecificName']];
				$specModel->add($spec);
			}
		}
		if(!$isSelf) {
			$tagsList = $ProductTagListModel->where("pid=" . $id)->select();
			foreach ($tagsList as $key => $value) {
				$value["pid"] = $newProductId;
				unset($value["id"]);
				$ProductTagListModel->add($value);
			}
		}else{
			$tagList = $ProductTagListModel->alias("a")
				->join("inner join wx_module_product_tag b on a.tagId=b.id")
				->field("b.*")
				->where("a.pid=$id")
				->select();
			foreach($tagList as $l=>$tag){
				$tagWhere['fromCustomerId']=array("eq",$cid);
				$tagWhere['name'] = array("eq",$tag['name']);
				$tagResult = $ProductTagModel->where($tagWhere)->find();
				if(!$tagResult){
					unset($tag['id']);
					$tag['fromCustomerId']=$customerId;
					$tagId = $ProductTagModel->add($tag);
				}else{
					$tagId = $tagResult['id'];
				}
				$tagData=null;
				$tagData['tagId']=$tagId;
				$tagData['pid']=$newProductId;
				$ProductTagListModel->add($tagData);
			}
		}
		$shareInfo = $shareBaseModel->where("moduleId=".$id." and module = 'product'")->find();
		$shareInfo["moduleId"]=$newProductId;
		$shareBaseId = $shareInfo["id"];
		unset($shareInfo["id"]);
		$shareInfo["createTime"] = $time;
		$newShareBaseId = $shareBaseModel->add($shareInfo);
		$shareMaterialInfo = $shareMaterModel->where("sId=".$shareBaseId)->find();
		unset($shareMaterialInfo["id"]);
		$shareMaterialInfo["sId"]=$newShareBaseId;
		$shareMaterId = $shareMaterModel->add($shareMaterialInfo);
		if(!$isSelf){
			if($shareMaterId){
				$result = new stdClass();
				$result->code = 0;
				$result->productId=$newProductId;
				Output::instance()->object($result);
			}else{
				Output::instance()->resultCode(code_sql_error);
				return;
			}
		}

	}
	//商品复制到其他商城
	public function copyProducts($ids,$cId){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$ids = explode(",",$ids);
		foreach($ids as $value){
			self::copyProductById($value,$cId,1);
		}
		Output::instance()->resultCode();
	}

	public function getCustomerUser(){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
		Session::switchCustomer(0);
		$CustomerUser = D('customer_user');
		$where['csu.status'] = 'open';
		$where['cu.role'] = 'C';
        /**
         * 这里使用了一个表关联, 查询wx_customer的id
         * 20170713 - customer底层多账号支持修改, 这里考虑它只用到一个cu.id, 所以不会有什么影响, 故没有修改
         * LLyeap_wx_customer修改
         */
		$arr = $CustomerUser->alias('csu')
			->join("LEFT JOIN  wx_customer as cu ON cu.id = csu.customerId")
			->where($where)
			->field("cu.id,csu.loginName,csu.fullName,csu.customerId,csu.updateTime")
			->group("customerId")
			->select();
		$result['mimallList']=$arr;
		Output::instance()->object($result);
	}
	public function updateOrderSuccessByTime(){
		$ip = $_SERVER["REMOTE_ADDR"];
		log::write('taskOrderCallback---ipOne:'.$ip);
	}

    /**
     * 定时任务请求,定时修改已发货订单的状态为交易成功(即默认收货时间[普通商品默认7天|海外直邮默认20天->改为45天])
     * (apache服务器/var/spool/cron/root - 0 20 * * * /usr/bin/curl http://www.mboxone.com/wx/Product/updateOrderSuccessByTime.json >> test.log)
     *
     * @param int $timeDay  过期期限
     * @modify lilei<LL_strive@163.com> 2017-05-15
     */
    public function updateOrderSuccessByTimeTwo($timeDay = 7)
    {
		$ip = $_SERVER["REMOTE_ADDR"];
		log::write('taskOrderCallback---ip:'.$ip);

		$datatime = date('Y-m-d H:i:s');
        Session::switchCustomer(0);
        $ProductOrderModel = M("module_product_order"); //订单表
        $timerLog = M("module_timer_log");    //定时器日志表
        $orderDetail = M("module_product_order_detail");
        $where["status"] = "delivered";
        $arr = $ProductOrderModel->where($where)->select();
        //当前时间-7天
        Log::write("定时任务执行:" . $ProductOrderModel->getlastsql());
//        echo $nowTime;
//        echo $strNowTime;
//        echo $ProductOrderModel->getLastSql();
        $timerStatus = 1;  //所有的记录更新状态  0成功 1失败
        $oids = '';  //更改的订单编号
        foreach ($arr as $key => $val) {
            $cid = $val["fromCustomerId"];
            Session::switchCustomer($cid);
            if ($val['proSource']) {
                $timeDay = 45; // lilei修改, 20 -> 45
            } else {
                $timeDay = 7;
            }
            $nowTime = date('Y-m-d H:i:s', strtotime("$datatime -$timeDay day"));
            $strNowTime = strtotime($nowTime);
            if (strtotime($val["updateTime"]) < $strNowTime) {
//                echo $ProductOrderModel->getLastSql();
//                $data["status"]="ok";
//                $data["updateTime"] = $datatime;
//                $whereone["id"]=$val["id"];
//                $changeStatus=$ProductOrderModel->where($whereone)->save($data);
                // 更新成功 调用更改订单状态及分配佣金
                $changeStatus = self::myqupdateDividents($val["id"]);
                $oids .= $val["id"] . ',';
                if (false !== $changeStatus) {
                    if ($val["isTeam"] == 1) {
                        Log::write("订单标编号：" . $val["id"] . "  更改状态: " . $changeStatus . "  订单更新时间: " . $val["updateTime"]);
                        R('Tuan/tuanBackMoney', array($val["id"]));
                    }
//                    更新成功 调用更改订单状态及分配佣金
//                    self::updateOrderByOrderId($val["id"]);
                } else {
                    $timerStatus = 0;
//                    更新失败
                }
//                self::updateOrderByOrderId($changeStatus);
//                echo "   ".$changeStatus."    ";
//                echo 	$ProductOrderModel->getLastSql();

            }
        }

        $timeData["createTime"] = $datatime;
        $timeData["status"] = $timerStatus;
        $timeData["moudle"] = "product";
        $timeData["oids"] = substr($oids, 0, strlen($oids) - 1);
        $timeid = $timerLog->add($timeData);

//        var_dump($arr);
//        echo  date('Y-m-d H:i:s')."from updateOrderSuccessByTime  \n";
//        log::write(date('Y-m-d H:i:s')."updateOrderSuccessByTime");

    }
		public function SendDeliveredNotice($oid,$cid,$deliveryTime,$orderTime,$serialNumber,$userName){
		
			Session::switchCustomer(0);
			$orderDetail = M("module_product_order_detail");
			Session::switchCustomer($cid);
			$TemplateModel = M("template_messages");
			$isFormorder = $orderDetail->alias('a')
				->join('inner join wx_module_product_order b on b.id=a.oid')
				->where(['a.oid'=>$oid])
				->field('b.type,b.orderType,a.name')
				->find();

			if($isFormorder['type'] != ORDER_TYPE_FORM){
				$productInfo = $orderDetail->alias("a")
					->join("inner join wx_module_product b on a.pid=b.id")
					->join("inner join wx_module_product_order c on a.oid=c.id")
					->join("wx_module_mill_par d on c.playOrderId=d.id")
					->field("group_concat(b.name) as name,c.orderType,a.pid,d.perId,c.isActivity")
					->where("a.oid=$oid")
					->find();
			}
			$productName = $productInfo["name"];
			if( $productInfo['isActivity']) { //报名已确认
				$twhere['status'] = order_status_confirmsign;
				$templatemsg = $TemplateModel->where($twhere)->find();
				$templateId = $templatemsg['templateId'];
				$orderInfo = $orderDetail->alias("a")
					->join("inner join wx_module_product b on a.pid=b.id")
					->where("a.oid=$oid")
					->field("a.name,b.activityinfo")
					->find();
				$activityinfo = json_decode($orderInfo['activityinfo'],true);
				$data['first'] = array('value'=> '亲，您的报名已经确认！相遇原是注定，活动因你精彩。','color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $orderInfo['name'],'color'=>'#173177');
				$data['keyword2'] = array('value'=> $activityinfo['activityTime'],'color'=>'#173177');
				$data['keyword3'] = array('value'=> $activityinfo['activityPlace'],'color'=>'#173177');
				$data['remark'] = array('value'=> '查看报名详情',"color"=>'#008000');
				$url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
					"&module=product&method=getOrderDetail&params=%7B%22tplid%22:1,%22id%22:".$oid."%7D";
			}else if($productInfo["orderType"]==3){
				$twhere['status'] = order_status_ok;
				$templatemsg = $TemplateModel->where($twhere)->find();
				$templateId = $templatemsg['templateId'];
				$data['first'] = array('value'=> '夺宝大富翁开奖啦！您本次运气还差一点点，再试试手气吧，说不定下一个抽中的就是你喔！','color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $serialNumber,'color'=>'#173177');
				$data['keyword2'] = array('value'=> $productName,'color'=>'#173177');
				$data['keyword3'] = array('value'=> $orderTime,'color'=>'#173177');
				$data['keyword4'] = array('value'=> $deliveryTime,'color'=>'#173177');
				$data['keyword5'] = array('value'=> date("Y-m-d H:i:s",time()),'color'=>'#173177');
				$data['remark'] = array('value'=> '点击查看开奖结果',"color"=>'#008000');
				$url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
                            "&module=product&method=getProduct&params=%7B%22id%22%3A%22".$productInfo["pid"]."%22%2C%22periodId%22%3A%22".$productInfo["perId"]."%22%7D";
			}else if($isFormorder["orderType"]==ORDER_ORDERTYPE_NINE){
				$productName = $isFormorder['name'];
				$twhere['status'] = order_status_formOk;
				$templatemsg = $TemplateModel->where($twhere)->find();
				$templateId = $templatemsg['templateId'];
				$data['first'] = array('value'=>'您提交的信息已确认成功。' ,'color'=>"#00BD00");
				$data['keyword1'] = array('value'=> $serialNumber,'color'=>'#173177');
				$data['keyword2'] = array('value'=> $productName,'color'=>'#173177');
				$data['remark'] = array('value'=>'点击查看订单信息详情' ,"color"=>'#00BD00');
				$url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
					"&module=product&method=getOrderDetail&params=%7B%22id%22:".$oid."%7D";
			}else{
				$twhere['status'] = order_status_ok;
				$templatemsg = $TemplateModel->where($twhere)->find();
				$templateId = $templatemsg['templateId'];
				$tempParam = new stdClass();
                $tempParam->id = $oid;
				$red = Module::callModule("product",null,"commentRequire",$tempParam);
				if($red){
				    $first = '您的订单已经确认收货。';
				    $remark = '去晒单，拿红包！点我前往，手慢无！';
                }else{
                    $first = '您的订单已经确认收货。';
                    $remark = '点击查看详情';
                }
				$data['first'] = array('value'=>$first ,'color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $serialNumber,'color'=>'#173177');
				$data['keyword2'] = array('value'=> $productName,'color'=>'#173177');
				$data['keyword3'] = array('value'=> $orderTime,'color'=>'#173177');
				$data['keyword4'] = array('value'=> $deliveryTime,'color'=>'#173177');
				$data['keyword5'] = array('value'=> date("Y-m-d H:i:s",time()),'color'=>'#173177');
				$data['remark'] = array('value'=>$remark ,"color"=>'#008000');
				$url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
					"&module=product&method=getOrderDetail&params=%7B%22tplid%22:1,%22id%22:".$oid."%7D";
			}
			$toUser = $userName;
			$template_id = $templateId;
			$url = urlencode($url);
			$topcolor = "#FF0000";
			//data得转json
			//Log::write('jie---888|'.$toUser.'|'.$template_id.'|'.print_r($data, true));
			$result = WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);
			return $result;
		}
		//订单拆分
		public function splitOrder($oid,$dids){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$cid = Session::$user["customerId"];
			Session::switchCustomer(0);
			$orderModel = M("module_product_order");
			$orderDetail = M("module_product_order_detail");
			Session::switchCustomer($cid);
			$dids = explode(",",$dids);
			$proCount = $orderDetail->where("oid=$oid")->count();
			if(count($dids)>=$proCount){
				Output::instance()->resultCode(1,"所选商品过多！");
				return;
			}
			$orderModel->startTrans();
			$detailWhere['id']=array("in",$dids);
			$detailInfo = $orderDetail->where($detailWhere)->field("sum(price*count) as price,sum(ppat) as ppat")->find();
			$orderInfo = $orderModel->where("id=$oid")->find();
			unset($orderInfo['id']);
			unset($orderInfo['serialNumber']);
			unset($orderInfo['userCouponId']);
			unset($orderInfo['couponName']);
			unset($orderInfo['couponMoney']);
			unset($orderInfo['logisticsId']);
			unset($orderInfo['logisticsCost']);
			$oldData['price']=$orderInfo['price']-$detailInfo['price'];
			$oldData['ppat']=$orderInfo['ppat']-$detailInfo['ppat'];
			$oldResult = $orderModel->where("id=$oid")->save($oldData);
			if($oldResult===false){
				$orderModel->rollback();
				Output::instance()->resultCode(code_sql_error);
				return;
			}
			$orderInfo['price']=$detailInfo['price'];
			$orderInfo['ppat']=$detailInfo['ppat'];
			$newOrderId = $orderModel->add($orderInfo);
			if($newOrderId){
				$orderDetail->where($detailWhere)->setField("oid",$newOrderId);
				$newData['serialNumber'] = self::createOrderSerialNumber($newOrderId,$orderInfo['fromCustomerId']);
				$oldResult = $orderModel->where("id=$newOrderId")->save($newData);
				if($oldResult===false){
					$orderModel->rollback();
					Output::instance()->resultCode(code_sql_error);
					return;
				}else{
					$orderModel->commit();
					Output::instance()->resultCode();
				}
			}else{
				$orderModel->rollback();
				Output::instance()->resultCode(code_sql_error);
				return;
			}


		}
	private static function createOrderSerialNumber($ids, $customerId) {
		if (!strstr($ids, ',')) {
			$id = $ids;
		} else {
			// 如果拆单则使用第一个订单的id
			$id = substr($ids,0,strpos($ids,','));
		}

		$length = strlen($id);
		if ($length >= 3) {
			$id = substr($id, -3);
		} else {
			$id = str_pad($id, 3, '0', STR_PAD_LEFT);
		}
		$sn = $customerId . date("ymdHis") . $id;
		return $sn;
	}
	//众筹档位设置
	public function crowdFundingStallSet($pid,$id,$restrictPerson,$restrictAmount,$person,$amount,$drawStall,$drawPerson,$stallDescribe){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$crowdfundingModel = M("module_product_crowdfunding");
		Session::switchCustomer($cid);
		$crowfundingInfo = $crowdfundingModel->where("specId=$id and cid=$cid and pid = $pid")->find();
		$stallId=$crowfundingInfo['id'];
		$data['pid']=$pid;
		$data['cid']=$cid;
		$data['specId']=$id;
		$data['restrictPerson']=$restrictPerson;
		$data['restrictAmount']=$restrictAmount;
		$data['person']=$person;
		$data['amount']=$amount;
		$data['drawStall']=$drawStall;
		$data['drawPerson']=$drawPerson;
		$data['stallDescribe']=$stallDescribe;
		if($stallId){
			$data['surplusPerson']=$person-$crowfundingInfo['supportPerson'];
			$data['surplusAmount']=$amount-$crowfundingInfo['supportAmount'];
			$result = $crowdfundingModel->where("id=$stallId")->save($data);
		}else{
			$data['surplusPerson']=$person;
			$data['surplusAmount']=$amount;
			$result = $crowdfundingModel->add($data);
		}
		if($result!==false){
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}
	public function getCrowdFundingStall($pid,$id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$crowdfundingModel = M("module_product_crowdfunding");
		Session::switchCustomer($cid);
		$result = $crowdfundingModel->where("specId=$id and cid=$cid and pid = $pid")->find();
		Output::instance()->object($result);
	}


    // ============================ dashBoard

    public function productDashBoard($start = 0, $limit = 10, $status = 'delivering', $orderType = 'buy') {

        /** 1. 获得当前用户id */
        $retVal = Session::init();
        if (!$retVal) { // 如果该用户未登录, 则为非法用户, 返回
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /** 2. 实例化数据模型 */
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $OrderModel = M("module_product_order");
        Session::switchCustomer($cid);

        /** 3. 组合查询数据的where条件 */
        $where = [
            'fromCustomerId'    => $cid,
            'deleted'   => 0,
            'status'    => $status,
            'type'      => $orderType
        ];

        $orders = $OrderModel
            ->where($where)
            ->field('id, serialNumber')
            ->limit($start, $limit)
            ->order('id desc')
            ->select();

        $result = [
            'dashTitle' => '订单看板(待发货)',
            'dashType'  => [
                [
                    'typeName'  => '表格',
                    'typeIcon'  => 'iconfont icon-pingtai',
                    'typeFlag'  => 'table'
                ],
                [
                    'typeName'  => '折线图',
                    'typeIcon'  => 'iconfont icon-pingtai',
                    'typeFlag'  => 'line'
                ],
                [
                    'typeName'  => '柱状图',
                    'typeIcon'  => 'iconfont icon-pingtai',
                    'typeFlag'  => 'bar'
                ],
                [
                    'typeName'  => '饼图',
                    'typeIcon'  => 'iconfont icon-pingtai',
                    'typeFlag'  => 'pie'
                ]
            ],
            'dashInfo' => [
                'table' => [
                    'columns'   => [
                        [
                            'title' => '序号',
                            'field' => 'id',
                            'width' => '25%',
                            'align' => 'center',
                            'valign'    => 'middle'
                        ],
                        [
                            'title' => '编号',
                            'field' => 'serialNumber',
                            'width' => '25%',
                            'align' => 'center',
                            'valign'    => 'middle'
                        ]
                    ],
                    'data'      => $orders
                ],
                'line'  => [
                    'option'    => [
                        'title' => [
                            'text'  => '测试折线'
                        ],
                        'legend'    => [
//                            [
//                                'value' => 'partake_count',
//                                'name'  => '销量',
//                                'color' => '#5fbeaa',
//                                'type'  => 'line'
//                            ],
//                            [
//                                'value' => 'partake_count',
//                                'name'  => '库存',
//                                'color' => '#5fbeaa',
//                                'type'  => 'line'
//                            ]
                        ],
                        'grid'  => [
							'show'	=> false
                        ],
                        'xAxis' => [
                            'min'   => 3,
                            'max'   => 10,
                            'type'  => 'value'
                        ],
                        'yAxis' => [
                            'min'   => 1000,
                            'max'   => 9999,
                            'type'  => 'value'
                        ],
                        'series'    => [
                            [
                                'type'       => 'line',
                                'smooth'     => true,
                                'symbolSize' =>  'symbolSize',
                                'data'       =>  [
                                    [3, 5000], [4, 6000], [7, 5500], [8, 7000], [9, 8000], [10, 9999]
                                ]
                            ]
                        ]
                    ]
                ],
                'bar'   => [
                    'option'    => [
                        'title' => [
                            'text'  => '测试柱状图'
                        ],
                        'legend'    => [
//                            [
//                                'value' => 'partake_count',
//                                'name'  => '销量',
//                                'color' => '#5fbeaa',
//                                'type'  => 'line'
//                            ],
//                            [
//                                'value' => 'partake_count',
//                                'name'  => '库存',
//                                'color' => '#5fbeaa',
//                                'type'  => 'line'
//                            ]
                        ],
                        'grid'  => [
                            'show'	=> false
                        ],
                        'xAxis' => [
                            'type'  => 'category',
                            'data'  => ['one', 'two', 'three'],
                            'axisTick'  => [
                                'alignWithLabel'    => true
                            ]
                        ],
                        'yAxis' => [
                            'type'  => 'value'
                        ],
                        'series'    => [
                            [
                                'type'       => 'bar',
                                'smooth'     => true,
                                'symbolSize' =>  'symbolSize',
                                'data'       =>  [
                                    10, 50, 34
                                ]
                            ]
                        ]
                    ],
                ],
                'pie'   => [
                    'option'    => [
                        'title' => [
                            'text'      => '测试饼图',
                            'subtext'   => '纯属虚构',
                            'x'         => 'center',
                        ],
                        'legend'    => [
                            'trigger'   => 'item',
                            'formatter' => '{a} <br/>{b} : {c} ({d}%)'
                        ],
                        'legend'    => [
                            'orient'    => 'vertical',
                            'left'      => 'left',
                            'data'      => [
                                '直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎'
                            ]
                        ],
                        'series'    => [
                            [
                                'name'   => '访问来源',
                                'type'   => 'pie',
                                'radius' => '55%',
                                'center' =>  ['50%', '60%'],
                                'data'   =>  [
                                    ['value' => 335, 'name' => '直接访问'],
                                    ['value' => 310, 'name' => '邮件营销'],
                                    ['value' => 234, 'name' => '联盟广告'],
                                    ['value' => 135, 'name' => '视频广告'],
                                    ['value' => 1548, 'name' => '搜索引擎']
                                ]
                            ]
                        ]
                    ],
                ]
            ]
        ];

        Output::instance()->object($result);
    }
	public function getCustomizedList($name=null,$start=0,$limit=10){
		$retVal = Session::init();
		if (!$retVal) { // 如果该用户未登录, 则为非法用户, 返回
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/** 2. 实例化数据模型 */
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$customizedModel = M("module_customized");
		Session::switchCustomer($cid);
		$where['deleted']=array('eq',0);
		$name?$where['name'] =array('like',"%$name%"):"";
		$list = $customizedModel
			->where($where)
			->limit($start,$limit)
			->order('updateTime desc')
			->select();
		if($list){
			$count = $customizedModel->where($where)->count();
			Output::instance()->objArray($list,$count);
		}else{
			Output::instance()->resultCode();
		}

	}
	//保存修改常用定制信息
	public function saveCustomized($name,$customizedInfo,$id=null){
		$retVal = Session::init();
		if (!$retVal) { // 如果该用户未登录, 则为非法用户, 返回
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/** 2. 实例化数据模型 */
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$customizedModel = M("module_customized");
		Session::switchCustomer($cid);
		$data['name'] = $name;
		$data['customizedInfo'] = $customizedInfo;
		if($id){
			$data['updateTime'] = date("Y-m-d H:i:s");
			$result = $customizedModel->where("id=$id")->save($data);
		}else{
			$data['createTime'] = date("Y-m-d H:i:s");
			$data['cId'] = $cid;
			$result = $customizedModel->add($data);
		}
		if($result!==false){
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}
	//删除定制信息
	public function deletedCustomized($id){
		$retVal = Session::init();
		if (!$retVal) { // 如果该用户未登录, 则为非法用户, 返回
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/** 2. 实例化数据模型 */
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$customizedModel = M("module_customized");
		Session::switchCustomer($cid);
		$data['deleted'] = 1;
		$data['updateTime'] = date("Y-m-d H:i:s");
		$result = $customizedModel->where("id=$id")->save($data);
		if($result!==false){
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}
	//定时任务检测秒杀商品结束
	public function detectionSpikeProduct(){
		$productModel = M("module_product");
		$productTag = M("module_product_tag_list");
		$where['deleted'] = array('eq',0);
		$where['isRemoved'] = array('eq',0);
		$where['playType'] = array('eq',4);
		$productList = $productModel->where($where)->field("id,json")->select();
		$time = time();
		foreach($productList as $key=>$value){
			$json = json_decode($value['json'],true);
			$endTime = strtotime($json['seckillEndTime']);
			$tagId = $json['seckillTagId'];
			if($time>$endTime){
				//重置为普通商品
				$productModel->where("id=".$value['id'])->setField('playType',0);
				//从秒杀栏位移除
				$tagId?$productTag->where("pid=".$value['id']." and tagId in ($tagId)")->delete():"";
			}
		}
		Output::instance()->resultCode();
	}

	/**
	 * 删除商品缓存数据,对商品数据新加的缓存, 需要在这添加
	 * @param $pid /商品id
	 * @param $cId /cid
	 */
	protected function cacheDel($pid, $cId){
		$redis = new RedisAPI();
		$redis->del('cid'.$cId.'pid'.$pid);
		$redis->del('cid'.$cId.'pid'.$pid.'productInfo');
		$redis->del('cid'.$cId.'pid'.$pid.'mallHue');
		$redis->del('cid'.$cId.'pid'.$pid.'firstSpec');
		$redis->del('cid'.$cId.'pid'.$pid.'firstSpecUrl');
		$redis->del('cid'.$cId.'pid'.$pid.'sizeUnit');
		$redis->del('cid'.$cId.'pid'.$pid.'arrSecSpec');
		$redis->del('cid'.$cId.'pid'.$pid.'arrSecSpecurl');
		$redis->del('cid'.$cId.'pid'.$pid.'colorUnit');
		$redis->del('cid'.$cId.'pid'.$pid.'template');
	}

	/*表单订单-----*/
	/**
	 * 获取表单订单列表
	 * @param null $serialNumber /订单号
	 * @param null $startTime	/开始时间
	 * @param null $endTime		/结束时间
	 * @param string $status	/状态
	 * @param string $order  	/排序
	 * @param string $by  		/排序规则
	 * @param int $start  		/分页
	 * @param int $limit  		/条数
	 * @return object
	 */
	public function getFormOrderList($serialNumber=null, $startTime=null, $endTime=null, $status='',$order='createTime',
									 $by='desc', $start=0, $limit=10)
	{
		$ret = Session::init();
		if(!$ret){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$order_tab = M('module_product_order');
		Session::switchCustomer($cid);
		//只涉及到表单信息
		$where = [];
		$where['a.fromCustomerId'] = $cid;
		$where['a.type'] = 'form';
		if($serialNumber){
			$where['a.serialNumber'] = ['like','%'.$serialNumber.'%'];
		}
		$whereTime = [];
		if($startTime){
			$where['_string'] = "a.createTime >='$startTime'";
		}
		if($endTime){
			$where['a.createTime'] = ['ELT', date('Y-m-d', strtotime("$endTime +1 day"))];
		}

		if($status){
			$where['a.status'] = $status;
		}
		$orderList = $order_tab->alias('a')
			->join('inner join wx_module_product_order_detail b on a.id=b.oid')
			->join('wx_'.$cid.'_user_weixin_info c on a.uId=c.userId')
			->join('wx_'.$cid.'_user d on a.uId=d.id')
			->join('wx_form e on b.pid=e.id')
			->where($where)
			->order($order.' '.$by)
			->limit($start, $limit)
			->field('a.id, a.serialNumber, a.createTime, a.status, a.price, a.fullName, a.phone, c.nickname,
			c.headimgurl, d.fullName as spareName, d.phone as sparePhone, b.name as formName,e.type as isPay,
			 b.pid as formId')
			->select();

		if($orderList == null){
			Output::instance()->object([
				'code'=>1,
				'msg'=>'暂无订单',
				'total'=>0,
				'results'=>[]
			]);
			return;
		}
		$results = [];
		foreach($orderList as $k=>$v){
			if($v['isPay'] == 1){
				if($v['status'] == ORDER_STATUS_PAYING){
					$v['changeStatus'] = [
						['name'=>'已关闭','val'=>'closed']
					];
				}else if($v['status'] == order_status_refund || $v['status'] == ORDER_STATUS_REFUNDEDPART) {
					$v['changeStatus'] = [
						['name'=>'已关闭','val'=>'closed'],
						['name'=>'已取消','val'=>'cancel']
					];
				}else if($v['status'] == order_status_delivering){
					$v['changeStatus'] = [
						['name'=>'已确认','val'=>'ok'],
						['name'=>'已取消','val'=>'cancel']
					];
				}else if($v['status'] == order_status_ok){
					$v['changeStatus'] = [
						['name'=>'已取消','val'=>'cancel']
					];
				}else if($v['status'] == order_status_cancel){
					$v['changeStatus'] = [
						['name'=>'已确认','val'=>'ok'],
						['name'=>'已关闭','val'=>'closed']
					];
				}else{
					$v['changeStatus'] = [];
				}
			}else{
				if($v['status'] == order_status_submission){
					$v['changeStatus'] = [
						['name'=>'已确认','val'=>'ok'],
						['name'=>'已关闭','val'=>'closed'],
						['name'=>'已取消','val'=>'cancel']
					];
				}else if($v['status'] == order_status_ok){
					$v['changeStatus'] = [
						['name'=>'已取消','val'=>'cancel']
					];
				}else if($v['status'] == order_status_cancel){
					$v['changeStatus'] = [
						['name'=>'已确认','val'=>'ok'],
						['name'=>'已关闭','val'=>'closed']
					];
				}else{
					$v['changeStatus'] = [];
				}
			}
			$results[$k] = $v;
		}
		$total = $order_tab->alias('a')
			->join('inner join wx_module_product_order_detail b on a.id=b.oid')
			->where($where)
			->field('a.id')
			->count();
		Output::instance()->object([
			'code'=>0,
			'msg'=>'ok',
			'total'=>$total,
			'results'=>$results
		]);
	}

	/**
	 * 获取订单详情
	 * @param $orderId /订单id
	 */
	public function getFormOrderDetail($orderId)
	{
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		$uid = Session::$user['userId'];
		Session::switchCustomer(0);
		$order_tab = M('module_product_order');
		$orderRefund_tab = M('module_product_order_refund');
		$quan_tab = M('miyouquan');
		Session::switchCustomer($cid);
		$userWx_tab = M('user_weixin_info');
		//分成等价格取表单设置时的价格,上一次分享人作为销售(密友)
		$orderInfo = $order_tab->alias('a')
			->join('inner join wx_module_product_order_detail b on a.id=b.oid')
			->join('wx_micontent f on a.moduleId=f.id')
			->join('wx_'.$cid.'_user_weixin_info c on a.uId=c.userId')
			->join('wx_'.$cid.'_user d on a.uId=d.id')
			->join('wx_form e on b.pid=e.id')
			->join('wx_'.$cid.'_user_weixin_info g on a.saleSource=g.userId')
			->join('wx_'.$cid.'_user_weixin_info h on a.miUid=h.userId')
			->join('wx_'.$cid.'_user_weixin_info i on a.refereeUid=i.userId')
			->join('wx_'.$cid.'_user_weixin_info j on a.parentRefereeUid=j.userId')
			->join('wx_'.$cid.'_user_weixin_info k on a.recommenderId=k.userId')
			->join('wx_form l on f.formId=l.id')
			->where(['a.id'=>$orderId])
			->field('a.id, a.serialNumber, a.uId, a.qid, a.miUid, a.createTime, a.status, a.price, a.fullName,a.refereeUid,
			 a.phone, a.wxTransactionId, a.payType,b.customizedInfo, b.pointConfig, b.isMiUserCut, b.isRefereeCut,b.isParentRefereeCut,
			  c.nickname,c.headimgurl, d.fullName as spareName,d.phone as sparePhone,e.formName, e.type as isPay,
			  e.payPrice, e.supplyPrice, e.platCut,e.saleCut,f.title,g.nickname as saleNickname,g.headimgurl as saleHeadImgUrl,
			  h.nickname as aname,h.headimgurl as aheadImgUrl, i.nickname as refereeName, i.headimgurl as refereeHeadImgUrl,
			  j.nickname as parentRefereeName,j.headimgurl as parentRefereeHeadImgUrl,k.nickname as recommendName,
			  k.headimgurl as recommendHeadImgUrl,a.parentRefereeUid,a.recommenderId, l.type as isPay')
			->find();
		if(!$orderInfo){
			R('Log/add',array('order',CODE_MODULEID_ORDER,'订单',op_other,$order_tab->getLastSql(),'传了不存在的订单id,登录用户uid='.$uid));
			Output::instance()->object([
				'code'=>1,
				'msg'=>'订单异常',
				'results'=>[]
			]);
			return;
		}

		//整理积分
		if($orderInfo['pointConfig']){
			$pointConfig = json_decode($orderInfo['pointConfig'], true);
			if($orderInfo['status'] !== order_status_ok){
				$pointConfig['buyerPoint'] = 0;
				$pointConfig['miPoint'] = 0;
				$pointConfig['preMiPoint'] = 0;
				$pointConfig['prePreMiPoint'] = 0;
				$pointConfig['recommenderPoint'] = 0;
			}
			empty($orderInfo['miUid'])?$pointConfig['miPoint']=0:'';
			empty($orderInfo['refereeUid'])?$pointConfig['preMiPoint']=0:'';
			empty($orderInfo['parentRefereeUid'])?$pointConfig['prePreMiPoint']=0:'';
			empty($orderInfo['recommenderId'])?$pointConfig['recommenderPoint']=0:'';
			$orderInfo['buyerPoint'] = $pointConfig['buyerPoint'];
			$orderInfo['miPoint'] = $pointConfig['miPoint'];
			$orderInfo['preMiPoint'] = $pointConfig['preMiPoint'];
			$orderInfo['prePreMiPoint'] = $pointConfig['prePreMiPoint'];
			$orderInfo['recommenderPoint'] = $pointConfig['recommenderPoint'];
		}
		if(!$orderInfo['isRefereeCut']){
			$orderInfo['isRefereeCut'] = '0.00';
		}

		//获取圈信息
		$quanInfo = [];
		if($orderInfo['qid']){
			$quanInfo = $quan_tab->where(['id'=>$orderInfo['qid'], 'cId'=>$cid])->field('name, logo')->find();
		}
		$orderInfo['quanInfo']['name'] = $quanInfo['name']?$quanInfo['name']:'';
		$orderInfo['quanInfo']['logo'] = $quanInfo['logo']?$quanInfo['logo']:'';
		//获取销售信息
		$saleInfo = [];
		if($orderInfo['miUid']){
			$saleInfo = $userWx_tab->where(['userId'=>$orderInfo['miUid']])->field('nickname, headimgurl')->find();
		}else{
			$saleInfo = $userWx_tab->where(['userId'=>$orderInfo['uId']])->field('nickname, headimgurl')->find();
		}
		//获取退款总额
		$refundMoney = $orderRefund_tab->where(['oid'=>$orderId, 'status'=>'ok'])->sum('refundPrice');
		$orderInfo['refundMoney'] = $refundMoney?$refundMoney:0;
		$orderInfo['saleInfo']['nickname'] = $saleInfo['nickname']?$saleInfo['nickname']:'';
		$orderInfo['saleInfo']['headimgurl'] = $saleInfo['headimgurl']?$saleInfo['headimgurl']:'';
		if($orderInfo['isPay'] == 1){
			if($orderInfo['status'] == ORDER_STATUS_PAYING || $orderInfo['status'] == order_status_refund || $orderInfo['status'] == ORDER_STATUS_REFUNDEDPART){
				$orderInfo['changeStatus'] = [
					['name'=>'已关闭','val'=>'closed']
				];
			}else if($orderInfo['status'] == order_status_delivering || $orderInfo['status'] == ORDER_STATUS_REFUNDING){
				$orderInfo['changeStatus'] = [
					['name'=>'已确认','val'=>'ok'],
					['name'=>'已取消','val'=>'cancel']
				];
			}else if($orderInfo['status'] == order_status_ok){
				$orderInfo['changeStatus'] = [
					['name'=>'已取消','val'=>'cancel']
				];
			}else if($orderInfo['status'] == order_status_cancel){
				$orderInfo['changeStatus'] = [
					['name'=>'已确认','val'=>'ok'],
					['name'=>'已关闭','val'=>'closed']
				];
			}else{
				$orderInfo['changeStatus'] = [];
			}
		}else{
			if($orderInfo['status'] == order_status_submission){
				$orderInfo['changeStatus'] = [
					['name'=>'已确认','val'=>'ok'],
					['name'=>'已关闭','val'=>'closed'],
					['name'=>'已取消','val'=>'cancel']
				];
			}else if($orderInfo['status'] == order_status_ok){
				$orderInfo['changeStatus'] = [
					['name'=>'已取消','val'=>'cancel']
				];
			}else if($orderInfo['status'] == order_status_cancel){
				$orderInfo['changeStatus'] = [
					['name'=>'已确认','val'=>'ok'],
					['name'=>'已关闭','val'=>'closed']
				];
			}else{
				$orderInfo['changeStatus'] = [];
			}
		}
		if($orderInfo['payType'] == 'wxpay'){
			$orderInfo['payTypeShow'] = '微信支付';
		}else if($orderInfo['payType'] == 'alipay'){
			$orderInfo['payTypeShow'] = '支付宝支付';
		}else{
			$orderInfo['payTypeShow'] = '其他';
		}
		$orderInfo['customizedInfo'] = json_decode($orderInfo['customizedInfo'], true);

		Output::instance()->object([
			'code'=>0,
			'msg'=>'ok',
			'results'=>$orderInfo
		]);
	}

	/**
	 * 更改表单订单状态
	 * @param $orderId /订单id
	 * @param $status	/订单状态 0待付款/，1已付款/，2已部分退款/，3已退款/，4已关闭，5已取消
	 * @param $isPay	/是否是支付订单
	 */
	public function updateFormOrderType($orderId, $status, $isPay)
	{
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		$uid = Session::$user['userId'];
		Session::switchCustomer(0);
		$order_tab = M('module_product_order');
		$shareRewardRet_tab = M('share_reward_result');
		$shareReward_tab = M('share_reward');
		$shareRewardVisit_tab = M('share_reward_visit_result');
		$CustomerMallSettingModel = D('customer_mall_setting');
		Session::switchCustomer($cid);
		$user_tab = M('user');
		$TemplateModel = M("template_messages");

		$order = $order_tab->alias('a')
			->join('wx_module_product_order_detail b on a.id=b.oid')
			->join('wx_'.$cid.'_user c on a.uId=c.id')
			->join('wx_micontent d on a.moduleId=d.id')
			->where(['a.id'=>$orderId])
			->field('a.*,b.name,c.userName,d.id as miContentId,d.rewardId,c.phone')
			->find();
		if($order == null){
			R('Log/add',array('order',CODE_MODULEID_ORDER,'订单',op_other,$order_tab->getLastSql(),'非法更改订单状态,登录用户uid='.$uid));
			Output::instance()->object([
				'code'=>1,
				'msg'=>'不存在的订单'
			]);
			return;
		}
		//更改是否合法
		try{
			if($isPay == 1){
				switch($order['status']){
					case order_status_ok:
						if($status !== 'cancel'){
							throw new Exception('非法状态值');
						}
						break;
					case order_status_cancel:
						if($status !== 'closed' && $status !== 'ok'){
							throw new Exception('非法状态值');
						}
						break;
					case order_status_closed:
						if($status){
							throw new Exception('关闭订单无法修改');
						}
						break;
				}
			}else{
				///Log::write('jie-----cancel1'.$order['status']);
				switch($order['status']){
					case order_status_submission:
						if($status !== 'closed' && $status !== 'cancel' && $status !== 'ok'){
							throw new Exception('非法状态值');
						}
						break;
					case order_status_ok:
						if($status !== 'cancel'){
							throw new Exception('非法状态值');
						}
						break;
					case order_status_cancel:
						if($status !== 'closed' && $status !== 'ok'){
							//Log::write('jie-----cancel2'.$status);
							throw new Exception('非法状态值');
						}
						break;
					case order_status_closed:
						if($status){
							throw new Exception('关闭订单无法修改');
						}
						break;
				}
			}
		}catch(Exception $e){
			R('Log/add',array('order',CODE_MODULEID_ORDER,'订单',op_other,$order_tab->getLastSql(),'非法更改订单状态,登录用户uid='.$uid));
			Output::instance()->object([
				'code'=>1,
				'msg'=>$e->getMessage(),
				'results'=>[]
			]);
			return;
		}
		M()->startTrans();
		$bool = $order_tab->where(['id'=>$orderId])->save(['status'=>$status]);
		if($bool && $status == 'ok'){
			/*如果存在分享奖励,且基于线索的,将产生一条分享奖励记录*/
			Log::write('rewardId:'.$order['rewardId']);
			if($order['rewardId']){
				$rewardCfg = $shareReward_tab->where(['cid'=>$cid,'id'=>$order['rewardId']])->find();
				if($rewardCfg['isClue']){
					$rewardMap = [];
					$rewardMap['cid'] = $cid;
					$rewardMap['rewardId'] = $order['rewardId'];
					$rewardMap['orderId'] = $orderId;
					$clueRewardRet = $shareRewardRet_tab->where($rewardMap)->getField('id');
					if(!$clueRewardRet && $rewardCfg['clueShareRemainder'] > 0){
						$visitRet = $shareRewardVisit_tab->where(['cid'=>$cid,'uid'=>$order['miUid'],
							'module'=>'micontent','moduleId'=>$order['miContentId']])->getField('visitCount');
						$clueCfg = [];
						$clueCfg['isClue'] = 1;
						$clueCfg['clueShareRemainder'] = $rewardCfg['clueShareRemainder'];
						$clueCfg['clueRewardType'] = $rewardCfg['clueRewardType'];
						$clueCfg['clueBlessings'] = $rewardCfg['clueBlessings'];
						$clueCfg['clueGiftName'] = $rewardCfg['clueGiftName'];
						$clueCfg['clueRedMoney'] = $rewardCfg['clueRedMoney'];
						$clueCfg['clueRewardImgs'] = $rewardCfg['clueRewardImgs'];
						$clueCfg['endTime'] = $rewardCfg['endTime'];
						$clueCfg['currentUid'] = $order['uId'];
						$rewardMap['module'] = 'micontent';
						$rewardMap['moduleId'] = $order['miContentId'];
						$rewardMap['uid'] = $order['miUid'];
						$rewardMap['rewardName'] = $rewardCfg['name'];
						$rewardMap['rewardJson'] = json_encode($clueCfg);
						$rewardMap['rewardCause'] = 2;
						$rewardMap['shareVisitNum'] = $visitRet;
						$rewardMap['rewardWay'] = $rewardCfg['clueRewardType'];
						$rewardMap['noGrantTime'] = date('Y-m-d H:i:s');
						$rewardMap['createTime'] = date('Y-m-d H:i:s');
						$saveRet = $shareRewardRet_tab->add($rewardMap);

						if(!$saveRet){
							Log::write('分享线索奖励结果保存失败cid:'.$cid.'|sql:'.$shareRewardRet_tab->getLastSql());
							M()->rollback();
							Output::instance()->object([
								'code'=>-1,
								'msg'=>'基于线索分享奖励产生失败',
								'results'=>[]
							]);
							return;
						}
						$rewardCfg['clueShareRemainder'] = $rewardCfg['clueShareRemainder']-1;
						$updateRet = $shareReward_tab->where(['id'=>$order['rewardId']])->save([
							'clueShareRemainder'=>$rewardCfg['clueShareRemainder'],
							'updateTime'=>date('Y-m-d H:i:s')
						]);
						if(!is_numeric($updateRet)){
							Log::write('更新基于线索剩余奖励份数失败cid:'.$cid.'|uid:'.$order['uId'].'|sql:'.$shareReward_tab->getLastSql());
							M()->rollback();
							Output::instance()->object([
								'code'=>-1,
								'msg'=>'更新分享奖励剩余份数失败',
								'results'=>[]
							]);
							return;
						}
						M()->commit();

						if($rewardCfg['clueRewardType'] !== 1){
							$sql = 'select userName from wx_'.$cid.'_user where id='.$order['miUid'];
							$miUidOpenid = M()->query($sql);
							$templateRedId = $TemplateModel->where(['status'=>'shareRewardClueConfirm'])->getField('templateId');
							if(!$templateRedId){
								Log::write('reward无效的模板id'.$TemplateModel->getLastSql());
							}
							$customer = WeixinApi::getCustomer();
							if($customer['mode']&&$customer['grantStatus']){
								$domainName = $customer["appid"];
								$http['RESOURCEURL']="http://".$domainName.".".C('NEWSERVER_HOST');
							}else{
								$http['RESOURCEURL'] = C("SERVER_HOST");

							}
							//
							$urls = $http['RESOURCEURL']."call.html?customerId=".$cid."&module=micontent&method=getRewardInfo&params=%7B%22micontentId%22%3A%22".$order['miContentId']."%22%2C%22rewardId%22%3A%22".$order['rewardId']."%22%7D";
							$data['first'] = array('value'=> '恭喜您,获得奖励礼品一份','color'=>"#743A3A");
							$data['keyword1'] = array('value'=> $rewardCfg['name'],'color'=>'#173177');	//活动
							$data['keyword2'] = array('value'=> $rewardCfg['clueGiftName'],'color'=>'#173177');//奖品					//奖品
							$data['keyword3'] = array('value'=> date('Y-m-d'),'color'=>'#173177');					//领取时间
							$data['remark'] = array('value'=>'点击提交领取信息',"color"=>'#008000');
							$url = urlencode($urls);
							$topcolor = "#FF0000";
							WeixinApi::sendTpl($miUidOpenid[0]['userName'], $templateRedId, $url,$topcolor,$data,true,$cid);
						}

						if($rewardCfg['clueRewardType'] == 1){
							$bool = ShareRewardAction::shareRewardMoneyGift($cid=null,$order['miUid'],$rewardCfg['clueRedMoney'],
								$rewardCfg['clueBlessings'],$order['rewardId'],$saveRet,$order['miContentId'],1);
							if(!$bool){
								Output::instance()->object([
									'code'=>-1,
									'msg'=>'基于线索奖励发送红包失败',
									'results'=>[]
								]);
								return;
							}
						}

					}
				}
			}
			//分成计算
			$bool = self::myqupdateDividents($orderId);
			if(!$bool){
				//M()->rollback();
				Output::instance()->object([
					'code'=>1,
					'msg'=>'订单分成失败',
					'results'=>[]
				]);
				return;
			}
            //20180723mh增加短信发送
            if ($order['phone']) {
                $params = new stdClass();
                $params->phone = $order['phone'];
                $params->module = 'nmpOrder' ;
                $params->status = 'confirm';
                $params->message = "您填写的表单信息已确认成功";
                Module::callModule('phone', NULL, 'sendSms', $params);
            }
		}
		M()->commit();
		if($bool && $status == order_status_cancel){
			$twhere['status'] = order_status_formOk;
			$templatemsg = $TemplateModel->where($twhere)->find();
			$templateId = $templatemsg['templateId'];
			$data['first'] = array('value'=>'您提交的信息没有被确认成功。' ,'color'=>"#FF0000");
			$data['keyword1'] = array('value'=> $order['serialNumber'],'color'=>'#173177');
			$data['keyword2'] = array('value'=> $order['name'],'color'=>'#173177');
			$data['remark'] = array('value'=>'点击查看订单信息详情' ,"color"=>'#008000');
			$url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
				"&module=product&method=getOrderDetail&params=%7B%22id%22:".$orderId."%7D";
			$toUser = $order['userName'];
			$template_id = $templateId;
			$url = urlencode($url);
			$topcolor = "#FF0000";
			$result = WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);

			/*只有当前的状态是"已确认"并且已经进行分成的订单才进行分成及积分的扣减*/
			if(($order['status'] == order_status_ok) && ($order['partnerAwardStatus'] == 1)){
				//扣减积分
				ProductOrder::deductPoint($orderId, $order);
				//扣减分成
				ProductOrder::deductionCut($orderId);
				ProductOrder::delVendorCut($orderId);
				//可再次进行分成以及扣减分成
				$oldorderarr['updateTime'] = date("Y-m-d H:i:s");
				$oldorderarr['partnerAwardStatus']=0;
				$updateRet = $order_tab->where(['id' => $orderId])->save($oldorderarr);
				if(!is_numeric($updateRet)){
					Log::write('更新分成状态失败:'.$order_tab->getLastSql());
				}
			}
		}
		Output::instance()->object([
			'code'=>0,
			'msg'=>'状态更新成功',
			'results'=>[]
		]);
		//TODO 发送模板消息
	}

	/**
	 * 表单订单退款
	 * @param $orderId	/订单id
	 * @param $refundMoney	/退款金额
	 * @param string $refundPwd	 /退款密码
	 */
	public function formOrderRefund($orderId, $refundMoney, $refundPwd)
	{
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$order_tab = M('module_product_order');
		$customer_user = M('customer_user');
		Session::switchCustomer($cid);
		$password = $customer_user->where(['id'=>session('id')])->getField('password');
		if(strcasecmp($password, Encryption::password($refundPwd)) != 0){
			Output::instance()->object([
				'code'=>1,
				'msg'=>'密码错误'
			]);
			return;
		}
		$orderInfo = $order_tab->alias('a')
			->join('inner join wx_module_product_order_detail b on a.id=b.oid')
			->join('inner join wx_form c on b.pid=c.id')
			->where(['a.id'=>$orderId,'c.cid'=>$cid])
			->field('a.status, c.type')
			->find();

		if($orderInfo == null){
			R('Log/add',array('order','20','订单',op_other,$order_tab->getLastSql(),'非法更改订单状态,登录用户uid='.$uid));
			Output::instance()->object([
				'code'=>1,
				'msg'=>'不存在的订单'
			]);
			return;
		}
		if($orderInfo['type'] == 2){
			Output::instance()->object([
				'code'=>1,
				'msg'=>'非付费表单,不可退款'
			]);
			return;
		}

		//退款操作是在已付款，已确认已取消情况下可以进行的，   但是已关闭就不可以退款了
		if($orderInfo['status'] !== order_status_delivering && ($orderInfo['status'] !== order_status_ok)
			&& ($orderInfo['status'] !== order_status_cancel)){
			Output::instance()->object([
				'code'=>1,
				'msg'=>'此状态订单无法退款'
			]);
			return;
		}
		self::orderRefund($orderId, $refundMoney, $refundPwd);
	}

	/**
	 * 获取表单订单的退款记录
	 * @param $orderId /订单id
	 */
	public function getFormOrderRefundList($orderId){
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$orderRefund_tab = M('module_product_order_refund');
		Session::switchCustomer($cid);

		$refundList = $orderRefund_tab->where(['oid'=>$orderId])->field('refundPrice, createTime, status')
			->order('createTime desc')->select();
		if($refundList == null){
			Output::instance()->object([
				'code'=>1,
				'msg'=>'暂无退款记录',
				'results'=>[]
			]);
			return;
		}
		$results = [];
		foreach($refundList as $k=>$v){
			if($v['status'] == 'ok'){
				$v['statusShow'] = '退款成功';
			}else if($v['status'] == 'error'){
				$v['statusShow'] = '退款失败';
			}else{
				$v['statusShow'] = $v['status'];
			}
			$results[$k] = $v;
		}
		Output::instance()->object([
			'code'=>0,
			'msg'=>'ok',
			'results'=>$results
		]);
	}
    /**获取所有规格的产品列表
     * @param string $name 商品名称搜索字段
     * @param int $start 分页起始
     * @param int $limit 分页偏移
     */
    public function  getAllSpecProduct( $name='',$start = 0, $limit = 25){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $ProductModel  = M('module_product');
       // $productUnit = M("module_product_unit");
        Session::switchCustomer($customerId);

        $condition['prod.deleted']=0;
        $condition['prod.fromCustomerId']=array("eq",$customerId);
        isset($name) && $name != null ? $condition["prod.name"] = array("like",'%'.$name.'%'):'';

        $arr = $ProductModel
            ->alias('prod')
            ->join('wx_module_product_specification spe on spe.pid = prod.id')
            ->join("wx_mivendor ven on prod.vId=ven.id")
            ->field('prod.id,prod.name,prod.picUrl,prod.brand,spe.inventoryCount,spe.firstSpecificName,spe.secSpecificName,ven.name as supplierName ')
            ->where($condition)->order("prod.updateTime desc")->limit($start, $limit)->select();

        if ($arr) {
            // foreach($arr as $key=>$value){
            //     $where_unit['pid'] = $value['id'];
            //     $where_unit['cid'] = $customerId;
            //     $unitInfo = $productUnit->where($where_unit)->select();
            //     $unitInfo = empty($unitInfo) ? [] : $unitInfo;
            //     $arr[$key]['unitInfo'] = $unitInfo;
            //     $arr[$key]['unitName'] = '';
            //     foreach ($unitInfo as $key1=>$value1) {
            //         if ($value1['isBasicUnit']) {
            //             $arr[$key]['unitName'] = $value1['unitName'];
            //             break;
            //         }else{
            //             continue;
            //         }
            //     }
            // }
            $count = $ProductModel
                ->alias('prod')
                    ->join('wx_module_product_specification spe on spe.pid = prod.id')
                    ->join("wx_mivendor ven on prod.vId=ven.id")
                    ->field('prod.id')
                    ->where($condition)
                    ->count();
             Output::instance()->objArray($arr,$count);
       }else {
            Output::instance()->resultCode();
        }
    }

	// 过滤掉emoji表情
	public function filterEmoji($str) {
		$str = preg_replace_callback(
			'/./u',
			function (array $match) {
				return strlen($match[0]) >= 4 ? '' : $match[0];
			},
			$str);

		return $str;
	}
}
